﻿// This software is the confidential and proprietary information of NetBay.
// Such confidential information should not be disclosed.
// NetBay copyright(c) 2012

#region

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Xml;
using AMA.Util;
using Aspose.Cells;
using Aspose.Cells.Rendering;
using Aspose.Pdf;
using Aspose.Pdf.Kit;
using Aspose.Slides;
using Aspose.Slides.Pptx;
using Aspose.Words;
using Aspose.Words.Drawing;
using Aspose.Words.Saving;
using GdPicture;
using ICSharpCode.SharpZipLib.Zip;
using NetBay.Core.BusinessEntities;
using NetBay.Core.BusinessEntities.Barcodes;
using NetBay.Core.BusinessEntities.Enum;
using NetBay.Core.Extensions;
using NetBay.Core.Log;
using NetBay.Core.Mail.SMTP.Assync;
using Rio.WCF.Services.Report;
using Rio.WCF.Services.helpers;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using Color = Aspose.Pdf.Color;
using Document = NetBay.Core.BusinessEntities.Document;
using Encoder = System.Drawing.Imaging.Encoder;
using Font = iTextSharp.text.Font;
using Image = System.Drawing.Image;
using License = Aspose.Words.License;
using PageSize = iTextSharp.text.PageSize;
using PdfOptions = Aspose.Words.Saving.PdfOptions;
using Rectangle = iTextSharp.text.Rectangle;
using SaveFormat = Aspose.Slides.Export.SaveFormat;
using Section = Aspose.Pdf.Section;
using Shape = Aspose.Slides.Shape;
using TiffCompression = GdPicture.TiffCompression;

#endregion

namespace Rio.WCF.Services
{
    [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
    public class RioWCFService : IWCFService
    {
        #region Readonly & Static Fields

        private static readonly object m_LockObject = new object();
        private readonly GdPictureImaging m_oGdPictureImaging;
        private readonly GdPicturePDF m_oGdPicturePDF;

        #endregion

        #region Fields

        private int m_iHeigth;
        private int m_iWidth;

        #endregion

        #region Constructors

        /// <summary>
        ///   Initializes a new instance of the <see cref="RioWCFService" /> class.
        /// </summary>
        public RioWCFService()
        {
            m_oGdPictureImaging = new GdPictureImaging();
            m_oGdPicturePDF = new GdPicturePDF();
            LicenseGdPicture();
        }

        #endregion

        #region Instance Properties

        public bool EnableMetaData
        {
            get
            {
                try
                {
                    if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings.Get("EnableMetaData")))
                        return bool.Parse(ConfigurationManager.AppSettings.Get("EnableMetaData"));
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
        }

        /// <summary>
        ///   Gets the enabled page count.
        /// </summary>
        /// <value> The enabled page count. </value>
        public bool EnabledPageCount
        {
            get
            {
                try
                {
                    if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings.Get("EnabledPageCount")))
                        return bool.Parse(ConfigurationManager.AppSettings.Get("EnabledPageCount"));
                    return true;
                }
                catch (Exception)
                {
                    return false;
                }
            }
        }

        #endregion

        #region Instance Methods

        /// <summary>
        ///   Delete a directory
        /// </summary>
        /// <param name="p_lstDirectoriesFullPath"> List of all documents to delete </param>
        /// <param name="p_oMessageRequest"> </param>
        public ReturnBoolean DeleteDirectoriesWithFullPath(List<string> p_lstDirectoriesFullPath,
                                                           MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo(
                "---DeleteDocumentWithFullPath-----------p_lstFileFullPath.count(" + p_lstDirectoriesFullPath.Count +
                ")-----------------");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            var l_oReturnBoolean = new ReturnBoolean {Value = true};
            try
            {
                foreach (
                    var l_sFileNamefullPath in
                        p_lstDirectoriesFullPath.Where(l_sFileNamefullPath => l_sFileNamefullPath != null))
                {
                    Treatments.DeleteDirectory(l_sFileNamefullPath);

                    // Deleting the cache for this file.
                    Treatments.DeleteDirectory(
                        Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory"),
                                     Path.GetFileName(l_sFileNamefullPath)));
                }
            }
            catch (Exception ex)
            {
                l_oReturnBoolean =
                    new ReturnBoolean(
                        "------------- EXCEPTION IN WCF DeleteDocumentWithFullPath EXCEPTION[" + DateTime.Now + "]",
                        new Exception(ex.Message))
                        {
                            ErrorCode = (int) ReturnObject.ErrorCodes.DeletingFileDuringImportError
                        };
                LogManager.Instance().LogError(l_oReturnBoolean.FullErrorMessage);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---DeleteDocumentWithFullPath---------------------------");
            LogManager.Instance().LogInfo("END OF WCF SERVICE CALL ---------------------");
            LogManager.Instance().LogInfo(
                "----------------------------------------------------------------------");

            return l_oReturnBoolean;
        }

        /// <summary>
        ///   Delete a document
        /// </summary>
        /// <param name="p_lstFileFullPath"> List of all documents to delete </param>
        /// <param name="p_oMessageRequest"> </param>
        public ReturnBoolean DeleteDocumentWithFullPath(List<string> p_lstFileFullPath, MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo(
                "---DeleteDocumentWithFullPath-----------p_lstFileFullPath.count(" + p_lstFileFullPath.Count +
                ")-----------------");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            var l_oReturnBoolean = new ReturnBoolean {Value = true};
            try
            {
                foreach (
                    var l_sFileNamefullPath in
                        p_lstFileFullPath.Where(l_sFileNamefullPath => l_sFileNamefullPath != null))
                {
                    File.Delete(l_sFileNamefullPath);
                    // Deleting the cache for this file.
                    Treatments.DeleteAllCacheFiles(Path.GetFileName(l_sFileNamefullPath));
                    //Treatments.DeleteDirectory(Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory"), Path.GetFileName(l_sFileNamefullPath)));
                }
            }
            catch (Exception ex)
            {
                l_oReturnBoolean =
                    new ReturnBoolean(
                        "------------- EXCEPTION IN WCF DeleteDocumentWithFullPath EXCEPTION[" + DateTime.Now + "]",
                        new Exception(ex.Message))
                        {
                            ErrorCode = (int) ReturnObject.ErrorCodes.DeletingFileDuringImportError
                        };
                LogManager.Instance().LogError(l_oReturnBoolean.FullErrorMessage);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---DeleteDocumentWithFullPath---------------------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");
            LogManager.Instance().LogInfo(
                "----------------------------------------------------------------------");

            return l_oReturnBoolean;
        }

        /// <summary>
        ///   Delete a document and its thumbnail
        /// </summary>
        /// <param name="p_lstDocumentName"> List of all document name to delete </param>
        /// <param name="p_iUserId"> User identifier </param>
        /// <param name="p_directoryPath"> Path to combine </param>
        /// <param name="p_oMessageRequest"> </param>
        /// <returns> the returnboolean object with the correspondant value </returns>
        public ReturnBoolean DeleteImportDocumentFromPath(List<string> p_lstDocumentName, long p_iUserId,
                                                          string p_directoryPath, MessageRequest p_oMessageRequest)
        {
            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            var l_oReturnBooleanImport = new ReturnBoolean();
            ReturnBoolean l_oReturnBooleanImportCurrent;

            l_oReturnBooleanImport.IsValid = true;

            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---DeleteImportDocumentFromPath------p_lstDocumentName(" +
                                          p_lstDocumentName + ")--p_iUserId(" + p_iUserId +
                                          ")--p_iUserId(" + p_directoryPath + ")--------------------" +
                                          DateTime.Now);

            var l_lstFileName = new List<string>();
            foreach (var l_oFileName in p_lstDocumentName)
            {
                #region Deleting ThumbNailImage

                var l_sImageFullPath = GetThumbDocumentFullPath(l_oFileName, p_iUserId, p_directoryPath);
                LogManager.Instance().LogInfo("------------ DELETING THUMB FILE [" + l_sImageFullPath +
                                              "]");
                l_lstFileName.Add(l_sImageFullPath);
                l_oReturnBooleanImportCurrent = DeleteDocumentWithFullPath(l_lstFileName, p_oMessageRequest);
                l_lstFileName.Clear();

                #endregion

                if (l_oReturnBooleanImportCurrent.IsValid)
                {
                    #region Deleting Original Image

                    l_sImageFullPath = GetImportDocumentFullPath(l_oFileName, p_iUserId, p_directoryPath);
                    LogManager.Instance().LogInfo("------------ DELETING ORIGINAL FILE [" +
                                                  l_sImageFullPath + "]");
                    l_lstFileName.Add(l_sImageFullPath);
                    l_oReturnBooleanImportCurrent = DeleteDocumentWithFullPath(l_lstFileName, p_oMessageRequest);
                    l_lstFileName.Clear();

                    if (!l_oReturnBooleanImportCurrent.IsValid)
                    {
                        l_oReturnBooleanImport.IsValid = false;
                        l_oReturnBooleanImport.ErrorCode = (int) ReturnObject.ErrorCodes.DeletingFileDuringImportError;
                        l_oReturnBooleanImport.ErrorMessageParametersList.Add(l_sImageFullPath);
                    }

                    #endregion
                }
                else
                {
                    l_oReturnBooleanImport.IsValid = false;
                    l_oReturnBooleanImport.ErrorCode = (int) ReturnObject.ErrorCodes.DeletingFileDuringImportError;
                    l_oReturnBooleanImport.ErrorMessageParametersList.Add(l_sImageFullPath);
                }

                //Deleting the cache
                Treatments.DeleteDirectory(
                    Path.Combine(
                        Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory"),
                                     p_iUserId.ToString()), l_oFileName));
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---DeleteImportDocumentFromPath---------------------------");
            LogManager.Instance().LogInfo("END OF WCF SERVICE CALL ---------------------");
            LogManager.Instance().LogInfo(
                "----------------------------------------------------------------------");
            return l_oReturnBooleanImport;
        }

        /// <summary>
        ///   Does the barcode recognition.
        /// </summary>
        /// <param name="files"> The files. </param>
        /// <param name="p_lUserId"> The P_L user id. </param>
        /// <param name="p_oMessageRequest"> The p_o message request. </param>
        /// <returns> </returns>
        public BarcodeResultItemCollection DoBarcodeRecognition(string file, long p_lUserId,
                                                                MessageRequest p_oMessageRequest)
        {
            BarcodeResultItemCollection collection = new BarcodeResultItemCollection();

            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---DoBarcodeReconition------file(" + file +
                                          ")--------------------" + DateTime.Now);

            try
            {
                //Get all files without directories
                using (Treatments traitement = new Treatments())
                {
                    var l_sImageFullPath = GetImportDocumentFullPath(file, p_lUserId);
                    collection = traitement.DoBarcodeRecognition(l_sImageFullPath);
                }
            }
            catch (Exception ex)
            {
                LogManager.Instance().LogError("------------Exception in DoBarcodeReconition" +
                                               ex.Message + " ----- " + DateTime.Now);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---DoBarcodeReconition-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return collection;
        }

        /// <summary>
        ///   Sample to transform the given document to an XPS one
        /// </summary>
        /// <param name="p_sFullPathFileNameToReturn"> </param>
        /// <param name="p_iStartPage"> </param>
        /// <param name="p_iEndPage"> </param>
        /// <param name="p_oMessageRequest"> </param>
        /// <param name="p_bImport"> </param>
        /// <param name="p_lUserId"> </param>
        /// <returns> </returns>
        public ReturnDoubleValue GetXPSDocumentByFullPath(string p_sFullPathFileNameToReturn, int p_iStartPage,
                                                          int p_iEndPage, MessageRequest p_oMessageRequest,
                                                          bool p_bImport = false, long p_lUserId = 0)
        {
            var l_oFileToReturnInfo = new FileInfo(p_sFullPathFileNameToReturn);

            if (!l_oFileToReturnInfo.Exists)
            {
                LogManager.Instance().LogInfo(p_lUserId +
                                              "-----------------------------GetDocumentByFullPath----- This file [" +
                                              l_oFileToReturnInfo.FullName +
                                              "] does not exists--------------");
                var l_oReturnDoubleValueError =
                    new ReturnDoubleValue("Exception in GetDocumentByFullPath. The file [" +
                                          l_oFileToReturnInfo.FullName + "] does not exists")
                        {ErrorCode = (int) ReturnObject.ErrorCodes.FileNotFound,};
                return l_oReturnDoubleValueError;
            }


            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo(p_lUserId + "WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo(p_lUserId +
                                          "------------- GetDocumentByFullPath-----p_sFullPathFileName[" +
                                          p_sFullPathFileNameToReturn + "]--p_iStartPage[" +
                                          p_iStartPage + "]--p_iEndPage[" + p_iEndPage +
                                          "]--------------");

            var l_oReturnDoubleValue = new ReturnDoubleValue(null, 0)
                                           {
                                               SecondValue =
                                                   GetNumberOfPageInDocument(
                                                       new FileInfo(l_oFileToReturnInfo.FullName), true)
                                           };

            MemoryStream mst = new MemoryStream();
            try
            {
                LogManager.Instance().LogInfo(p_lUserId + "----- File " + l_oFileToReturnInfo.FullName +
                                              " does not exists in cache ------");


                if (l_oFileToReturnInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.DOC.szGetDescription())
                    ||
                    l_oFileToReturnInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.DOCX.szGetDescription())
                    ||
                    l_oFileToReturnInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.RTF.szGetDescription()))
                {
                    #region DOC / RTF

                    #region Aspose licencing

                    var wordLicense = new License();
                    wordLicense.SetLicense("Aspose.Total.lic");

                    #endregion

                    var l_oWordDocument = new Aspose.Words.Document(l_oFileToReturnInfo.FullName);
                    var l_oImageOptionsNew = new ImageOptions
                                                 {
                                                     JpegQuality =
                                                         int.Parse(ConfigurationManager.AppSettings.Get("ImageQuality")),
                                                     Resolution =
                                                         float.Parse(
                                                             ConfigurationManager.AppSettings.Get("ImageResolution"))
                                                 };


                    //for (var i = 0; i < l_oWordDocument.PageCount; i++)
                    //{
                    //l_oWordDocument.SaveToImage(i, 1, Path.Combine(l_oCacheFileUniqueDirectory, i.ToString("00000") + "_" + Path.GetFileNameWithoutExtension(l_oFileToReturnInfo.FullName) + Constant.ImageFileFormat.JPG.szGetDescription()), l_oImageOptionsNew);
                    l_oWordDocument.SaveToXps(0, l_oWordDocument.PageCount, mst, null);
                    //}

                    #endregion
                }
            }
            catch
            {
            }

            l_oReturnDoubleValue.Value = mst.GetBuffer();
            return l_oReturnDoubleValue;
        }

        /// <summary>
        ///   Find a word in a powerpoint side
        /// </summary>
        /// <param name="p_oSlide"> </param>
        /// <param name="p_TextToFind"> </param>
        /// <returns> </returns>
        protected bool FindTextInPowerPointSlide(Slide p_oSlide, string p_TextToFind)
        {
            foreach (Shape l_oShape in p_oSlide.Shapes)
            {
                //if (l_oShape is OleObjectFrame)
                //{
                //    break;
                //}

                if (l_oShape.TextFrame != null)
                {
                    int l_iPos = l_oShape.TextFrame.Text.ToLower().IndexOf(p_TextToFind);
                    if (l_iPos >= 0)
                        return true;
                }
            }
            return false;
        }

        /// <summary>
        ///   Basic method to post a document with segment
        /// </summary>
        /// <param name="p_oDocumentSegment"> The serialized document as a Byte array </param>
        /// <param name="p_sDocumentName"> Document Name </param>
        /// <param name="p_iUserId"> The user identifier </param>
        /// <param name="p_oSegmentGuid"> The temporary segment identifier </param>
        /// <param name="p_iSegmentOrder"> The segment order </param>
        /// <param name="p_bLastSegment"> Indicate if thie current segment in the last one </param>
        /// <param name="p_bCreateThumbnail"> Trigger the thumbnail creation </param>
        /// <returns> The thumbnail with its document properties </returns>
        private ImageRio BasePostDocumentWithSegment(byte[] p_oDocumentSegment, string p_sDocumentName, long p_iUserId,
                                                     Guid p_oSegmentGuid, int p_iSegmentOrder, Boolean p_bLastSegment,
                                                     Boolean p_bCreateThumbnail = true)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---PostDocumentWithSegment-----p_sDocumentName[" +
                                          p_sDocumentName + "] p_iUserId[" + p_iUserId +
                                          "]  p_oSegmentGuid[" + p_oSegmentGuid + "]  p_iSegmentOrder[" +
                                          p_iSegmentOrder + "]  p_bLastSegment[" + p_bLastSegment + "]");

            var l_oImageRio = new ImageRio();

            try
            {
                //Checking that the directory exists
                var l_sTemporaryDirectory = ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory");
                var l_otempDir = Path.Combine(l_sTemporaryDirectory, p_oSegmentGuid.ToString("N"));
                Treatments.CheckDirectory(l_otempDir);

                var l_sFileName = Path.Combine(l_otempDir,
                                               p_sDocumentName + "_" + p_oSegmentGuid.ToString("N") + "." +
                                               p_iSegmentOrder.ToString("000000000000000"));
                LogManager.Instance().LogInfo("---------- Writing file-----[" + l_sFileName + "]");
                using (Stream l_oStream = File.Create(l_sFileName))
                {
                    l_oStream.Write(p_oDocumentSegment, 0, p_oDocumentSegment.Length);
                }

                var l_oDi = new DirectoryInfo(l_otempDir);
                var l_oRgFiles = l_oDi.GetFiles("*.*");
                var l_oOrderedFiles = l_oRgFiles.OrderBy(f => f.Name);
                if (p_bLastSegment)
                {
                    LogManager.Instance().LogInfo("---------- Rebuilding the file");

                    var l_sDocumentFileFullPath = GetImportDocumentFullPath(p_sDocumentName, p_iUserId);
                    Treatments.CheckDirectory(new FileInfo(l_sDocumentFileFullPath).DirectoryName);
                    var l_oOutputFS = File.Create(l_sDocumentFileFullPath);
                    JoinFiles(l_otempDir, l_oOutputFS);

                    foreach (var l_oFileInfo in l_oOrderedFiles)
                    {
                        LogManager.Instance().LogInfo("----------  Deleting file [" +
                                                      l_oFileInfo.FullName + "]");
                        File.Delete(l_oFileInfo.FullName);
                    }

                    var l_oTreatments = new Treatments
                                            {
                                                FillMetadataInImageRio = true,
                                                ImageRioToFillMetadata = l_oImageRio
                                            };

                    var l_bFileTransfered = false;
                    while (!l_bFileTransfered)
                    {
                        try
                        {
                            using (
                                new FileStream(l_sDocumentFileFullPath, FileMode.Open, FileAccess.Read,
                                               FileShare.ReadWrite))
                            {
                                l_bFileTransfered = true;
                            }
                        }
                            // Catch to wait until file is completely transfered
                        catch
                        {
                        }
                    }

                    if (p_bCreateThumbnail)
                    {
                        var l_sThumbnailOutputPath =
                            Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.OutputDirectory"),
                                         p_iUserId.ToString());
                        var l_sThumbFileNamefullPath = GetThumbDocumentFullPath(p_sDocumentName, p_iUserId);

                        Treatments.CheckDirectory(new FileInfo(l_sThumbnailOutputPath).DirectoryName);

                        l_oTreatments.CreateThumb(GetImportDocumentFullPath(p_sDocumentName, p_iUserId),
                                                  l_sThumbFileNamefullPath);


                        var l_oFileStream = new FileStream(l_sThumbFileNamefullPath, FileMode.Open, FileAccess.Read,
                                                           FileShare.ReadWrite);
                        var binary = StreamtoByteArray(l_oFileStream);
                        l_oFileStream.Close();
                        l_oFileStream.Dispose();

                        l_oImageRio.Img = binary;
                        l_oImageRio.Name = Path.GetFileName(l_sThumbFileNamefullPath);

                        FileInfo documentFileInfo = new FileInfo(l_sDocumentFileFullPath);

                        l_oImageRio.NumberPages = GetNumberOfPageInDocument(documentFileInfo);

                        if (documentFileInfo.Exists)
                            Treatments.FillMetadata(documentFileInfo, ref l_oImageRio, EnableMetaData);

                        //Added code to delete all archive
                        //Treatments.DeleteAllImportCacheFiles(p_iUserId, documentFileInfo.Name);


                        binary = null;
                    }

                    LogManager.Instance().LogInfo("---------- Deleting directory [" + l_otempDir + "]");
                    Treatments.DeleteDirectory(l_otempDir);
                    Treatments.DeleteDirectory(
                        Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory"),
                                     p_iUserId + "\\" + p_sDocumentName));
                }
            }
            catch (Exception ex)
            {
                l_oImageRio.IsValid = false;
                l_oImageRio.ErrorMessage = "------------- EXCEPTION IN WCF PostDocumentWithSegment EXCEPTION[" +
                                           DateTime.Now + "]Exception " + ex.Message;
                LogManager.Instance().LogError("EXCEPTION IN WCF PostDocumentWithSegment EXCEPTION[" +
                                               DateTime.Now + "] Exception " + ex.Message);
            }
            finally
            {
                LogManager.Instance().LogInfo(string.Empty);
                LogManager.Instance().LogInfo("---PostDocumentWithSegment-----------------");
                LogManager.Instance().LogInfo("END OF WCF SERVICE CALL ---------------------");
            }

            return l_oImageRio;
        }

        /// <summary>
        ///   Method that uses Aspose.slides to convert a powerpoint file to a pdf file
        /// </summary>
        /// <param name="p_sOriginalFileFullPath"> The source powerpoint file name </param>
        /// <param name="p_sDestinationFileFullPath"> the destination path where the pdf will be saved </param>
        private void ConvertPowerpointToPdf(string p_sOriginalFileFullPath, string p_sDestinationFileFullPath)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---------------------------Call of ConvertPowerpointToPdf");

            var l_oFileInfo = new FileInfo(p_sOriginalFileFullPath);
            if (!l_oFileInfo.Exists)
                throw new FileNotFoundException(" Exception in ConvertPowerpointToPdf. File not Found : [" +
                                                l_oFileInfo.FullName + "]");

            #region Aspose licencing

            var slideLicense = new Aspose.Slides.License();
            slideLicense.SetLicense("Aspose.Total.lic");

            #endregion

            var l_oPresentation = new Presentation(p_sOriginalFileFullPath);

            l_oPresentation.Save(p_sDestinationFileFullPath, SaveFormat.Pdf);
            LogManager.Instance().LogInfo(
                "---------------------------End of Call of ConvertPowerpointToPdf");
        }

        /// <summary>
        ///   Method that uses Aspose.slides to convert a powerpoint file to a pdf file
        /// </summary>
        /// <param name="p_sOriginalFileFullPath"> The source powerpoint file name </param>
        /// <param name="p_sDestinationFileFullPath"> the destination path where the pdf will be saved </param>
        private void ConvertPowerpointXToPdf(string p_sOriginalFileFullPath, string p_sDestinationFileFullPath)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---------------------------Call of ConvertPowerpointXToPdf");

            var l_oFileInfo = new FileInfo(p_sOriginalFileFullPath);
            if (!l_oFileInfo.Exists)
                throw new FileNotFoundException(" Exception in ConvertPowerpoinXtToPdf. File not Found : [" +
                                                l_oFileInfo.FullName + "]");

            #region Aspose licencing

            var slideLicense = new Aspose.Slides.License();
            slideLicense.SetLicense("Aspose.Total.lic");

            #endregion

            var l_oPresentation = new PresentationEx(p_sOriginalFileFullPath);
            l_oPresentation.Save(p_sDestinationFileFullPath, SaveFormat.Pdf);

            LogManager.Instance().LogInfo(
                "---------------------------End of Call of ConvertPowerpointXToPdf");
        }

        /// <summary>
        ///   Method that uses Aspose to convert a Text file to a pdf file
        /// </summary>
        /// <param name="p_sSourceFullPathFileName"> The source text file name </param>
        /// <param name="p_sDestinationlFullPathFileName"> the destination path where the pdf will be saved </param>
        private void ConvertTextToPdf(string p_sSourceFullPathFileName, string p_sDestinationlFullPathFileName)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---------------------------Call of ConvertWordToPdf");

            var l_oFileInfo = new FileInfo(p_sSourceFullPathFileName);
            if (!l_oFileInfo.Exists)
                throw new FileNotFoundException(" Exception in ConvertTextToPdf. File not Found : [" +
                                                l_oFileInfo.FullName + "]");

            #region Aspose licencing

            var sPdfLicense = new Aspose.Pdf.License();
            sPdfLicense.SetLicense("Aspose.Total.lic");

            #endregion

            //Instantiate Pdf pbject by calling its empty constructor
            var l_oPdfFile = new Pdf();
            var l_oSection = new Section(l_oPdfFile);
            //Create a new section in the Pdf object

            var l_oColor = new Color("White");
            l_oPdfFile.Author = "Rio";
            l_oPdfFile.Title = l_oFileInfo.Name;

            l_oSection.BackgroundColor = l_oColor;

            l_oPdfFile.Sections.Add(l_oSection);

            if (File.Exists(p_sSourceFullPathFileName))
            {
                var l_oObjReader = new StreamReader(p_sSourceFullPathFileName, Encoding.Default);
                // Read the file till the end of the file has come
                do
                {
                    //Create a new text paragraph & pass text to its constructor as argument
                    var l_oT2 = new Text(l_oSection);
                    l_oSection.Paragraphs.Add(l_oT2);

                    var l_oSegment1 = new Segment(l_oT2);
                    l_oT2.Segments.Add(l_oSegment1);
                    l_oSegment1.TextInfo.FontName = "Helvetica";
                    l_oSegment1.TextInfo.FontEncoding = "winansi";
                    l_oSegment1.Content = l_oObjReader.ReadLine();


                    // Read till the end of file
                } while (l_oObjReader.Peek() != -1);

                // Close the StreamReader object
                l_oObjReader.Close();
            }

            // Save the PDF file
            l_oPdfFile.Save(p_sDestinationlFullPathFileName);

            LogManager.Instance().LogInfo("---------------------------End of Call of ConvertWordToPdf");
        }

        /// <summary>
        ///   Method that uses Aspose.word to convert a Word file to a pdf file
        /// </summary>
        /// <param name="p_sSourceFullPathFileName"> The source word file name </param>
        /// <param name="p_sDestinationlFullPathFileName"> the destination path where the pdf will be saved </param>
        private void ConvertWordToPdf(string p_sSourceFullPathFileName, string p_sDestinationlFullPathFileName)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---------------------------Call of ConvertWordToPdf");

            var l_oFileInfo = new FileInfo(p_sSourceFullPathFileName);
            if (!l_oFileInfo.Exists)
                throw new FileNotFoundException(" Exception in ConvertWordToPdf. File not Found : [" +
                                                l_oFileInfo.FullName + "]");

            #region Aspose licencing

            var swordLicense = new License();
            swordLicense.SetLicense("Aspose.Total.lic");

            #endregion

            var l_oWordDoc = new Aspose.Words.Document(p_sSourceFullPathFileName);

            // Get all shapes.
            var shapes = l_oWordDoc.GetChildNodes(NodeType.Shape, true);

            // Make all shapes inline.
            foreach (Aspose.Words.Drawing.Shape shape in shapes)
                shape.WrapType = WrapType.Inline;

            var l_oPdfOptions = new PdfOptions
                                    {
                                        TextCompression = PdfTextCompression.None,
                                        IsPreserveFormFields = true,
                                        JpegQuality = 100,
                                    };

            l_oWordDoc.SaveToPdf(0, l_oWordDoc.PageCount, p_sDestinationlFullPathFileName, l_oPdfOptions);

            LogManager.Instance().LogInfo("---------------------------End of Call of ConvertWordToPdf");
        }

        /// <summary>
        ///   Method that uses Aspose.Cells to convert a XLS file to a pdf file
        /// </summary>
        /// <param name="p_sOriginalFileFullPath"> </param>
        /// <param name="p_sDestinationFileFullPath"> the destination path where the pdf will be saved </param>
        private void ConvertXlsToPdf(string p_sOriginalFileFullPath, string p_sDestinationFileFullPath)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---------------------------Call of ConvertXlsToPdf");


            string l_sTemporaryDir = Treatments.CreateTemporaryDirectory();
            try
            {
                #region Aspose licencing

                var xlsLicense = new Aspose.Cells.License();
                xlsLicense.SetLicense("Aspose.Total.lic");

                var pdfKitLicence = new Aspose.Pdf.Kit.License();
                pdfKitLicence.SetLicense("Aspose.Total.lic");

                var pdfLicense = new Aspose.Pdf.License();
                pdfLicense.SetLicense("Aspose.Total.lic");

                #endregion

                var l_oFileInfo = new FileInfo(p_sOriginalFileFullPath);
                if (!l_oFileInfo.Exists)
                    throw new FileNotFoundException(" Exception in ConvertXlsToPdf. File not Found : [" +
                                                    l_oFileInfo.FullName + "]");

                LogManager.Instance().LogInfo(
                    "------------ConvertXlsToPdf------------  Opening File [" + p_sOriginalFileFullPath + "]");

                //var l_sGuid = Guid.NewGuid().ToString("N");
                var l_lstImageWorksheetToDelete = new List<string>();

                var l_oWorkbook = new Workbook(l_oFileInfo.FullName);
                var l_oImgOptions = new ImageOrPrintOptions
                                        {
                                            ImageFormat = ImageFormat.Jpeg,
                                            IsImageFitToPage = true,
                                        };

                var l_iTotalPages = 0;
                for (var i = 0; i < l_oWorkbook.Worksheets.Count; i++)
                {
                    var sheet = l_oWorkbook.Worksheets[i];
                    sheet.IsGridlinesVisible = true;

                    //Setting the orientation to Portrait
                    sheet.PageSetup.Orientation = PageOrientationType.Landscape;

                    //Setting the paper size to Tabloid
                    sheet.PageSetup.PaperSize = PaperSizeType.PaperTabloid;

                    //Setting the print quality of the worksheet to 1200 dpi
                    sheet.PageSetup.PrintQuality = 1200;

                    var sheetRender = new SheetRender(sheet, l_oImgOptions);

                    l_iTotalPages = l_iTotalPages + sheetRender.PageCount;

                    for (var j = 0; j < sheetRender.PageCount; j++)
                    {
                        var l_sWorksheetImage = Path.Combine(l_sTemporaryDir, string.Format("{0}_{1}{2}",
                                                                                            i.ToString("00000"),
                                                                                            j.ToString("00000"),
                                                                                            Constant.ImageFileFormat.JPG
                                                                                                .szGetDescription()))
                            ;
                        l_lstImageWorksheetToDelete.Add(l_sWorksheetImage);
                        if (!File.Exists(l_sWorksheetImage))
                        {
                            sheetRender.ToImage(j, l_sWorksheetImage);
                        }
                    }
                }

                //We now create the pdf with all image created from the excel file
                var l_oPdfForExcel = new Pdf();

                foreach (var l_simage in l_lstImageWorksheetToDelete)
                {
                    LogManager.Instance().LogInfo(
                        "------------ConvertXlsToPdf------------ Ading file to pdf [" + l_simage + "]");
                    //Adding a new section to the pdf file
                    Section l_oSectionForExcel = l_oPdfForExcel.Sections.Add();
                    Text l_oTextForExcel = new Text(string.Empty);
                    l_oSectionForExcel.Paragraphs.Add(l_oTextForExcel);
                    l_oTextForExcel.IsFirstParagraph = true;
                    l_oSectionForExcel.BackgroundImageFile = l_simage;
                }

                LogManager.Instance().LogInfo(
                    "------------ConvertXlsToPdf------------ Saving pdf to [" + p_sDestinationFileFullPath + "]");
                l_oPdfForExcel.Save(p_sDestinationFileFullPath);
            }
            catch (Exception ex)
            {
                LogManager.Instance().LogError(
                    "-------------------------------------- Exception in ConvertXlsToPdf. Exception[" + ex +
                    "]");
                throw;
            }
            finally
            {
                //We now delete all images corresponding to all worksheets
                Treatments.DeleteDirectory(l_sTemporaryDir);
            }

            LogManager.Instance().LogInfo("---------------------------End of Call of ConvertXlsToPdf");
        }

        /// <summary>
        ///   Delete a directory
        /// </summary>
        /// <param name="p_sDirectoryPath"> The path of the directory </param>
        /// <param name="p_oMessageRequest"> </param>
        private ReturnBoolean DeleteDirectory(string p_sDirectoryPath, MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---DeleteDirectory-----p_sDirectoryPath[" + p_sDirectoryPath +
                                          "]");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            var l_oReturnBoolean = new ReturnBoolean();
            try
            {
                Treatments.DeleteDirectory(p_sDirectoryPath);
            }
            catch (Exception)
            {
                LogManager.Instance().LogError(
                    "------------- EXCEPTION IN WCF DeleteDirectory EXCEPTION[" + DateTime.Now + "]");
                l_oReturnBoolean.IsValid = false;
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---DeleteDirectory-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return l_oReturnBoolean;
        }

        /// <summary>
        ///   Find a word in an aspose converted memory stream
        /// </summary>
        /// <param name="p_oMemoryStream"> </param>
        /// <param name="p_sWordTofind"> </param>
        /// <returns> </returns>
        private bool FindWordInMemoryStream(MemoryStream p_oMemoryStream, string p_sWordTofind)
        {
            PdfExtractor l_oExtractor = new PdfExtractor();
            MemoryStream l_oCurrent_ms_output = new MemoryStream();


            l_oExtractor.BindPdf(p_oMemoryStream);
            l_oExtractor.ExtractText(Encoding.UTF8);

            l_oExtractor.GetText(l_oCurrent_ms_output);

            l_oCurrent_ms_output.Position = 0;

            StreamReader l_oCurrent_sr = new StreamReader(l_oCurrent_ms_output, Encoding.UTF8);
            string l_sResult = string.Empty;
            string l_sTempString = l_oCurrent_sr.ReadLine();

            while (l_sTempString != null)
            {
                l_sResult += l_sTempString;
                l_sTempString = l_oCurrent_sr.ReadLine();
            }

            if (l_sResult.ToLower().IndexOf(p_sWordTofind.ToLower()) != -1)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        ///   Return data from local icons
        /// </summary>
        /// <param name="p_sIconeName"> Name of the icon </param>
        /// <returns> </returns>
        private byte[] GetIconData(string p_sIconeName)
        {
            byte[] l_oBinary;
            try
            {
                var l_oFs =
                    new FileStream(
                        Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Format("Icones\\{0}", p_sIconeName)),
                        FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                l_oBinary = StreamtoByteArray(l_oFs);
                l_oFs.Dispose();
                l_oFs.Close();
            }
            catch (Exception)
            {
                var l_oFs = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Icones\\erreur.jpg"),
                                           FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                l_oBinary = StreamtoByteArray(l_oFs);
                l_oFs.Dispose();
                l_oFs.Close();
            }
            return l_oBinary;
        }

        /// <summary>
        ///   Return data from local icons
        /// </summary>
        /// <param name="p_sFolderName"> DirectoryName </param>
        /// <returns> </returns>
        private byte[] GetIconDataByFolderName(string p_sFolderName)
        {
            ImageRioType imgType = ImageRio.ConvertDirectoryNameToImageRioType(Path.GetFileName(p_sFolderName));
            if (imgType != ImageRioType.Unknown)
                return GetIconData(imgType.ToString() + Constant.ImageFileFormat.PNG.szGetDescription().ToLower());
            else
                return GetIconData("erreur.jpg");
        }

        /// <summary>
        ///   Gets the image from full path by user id.
        /// </summary>
        /// <param name="p_lstImageFullPath"> The P_LST image full path. </param>
        /// <param name="p_lstOriginalImageFullPath"> The P_LST original image full path. </param>
        /// <param name="p_lUserId"> The P_L user id. </param>
        /// <param name="p_directoryPath"> The p_directory path. </param>
        /// <param name="p_oMessageRequest"> The p_o message request. </param>
        /// <returns> </returns>
        private List<ImageRio> GetImageFromFullPathByUserId(List<string> p_lstImageFullPath,
                                                            List<string> p_lstOriginalImageFullPath, long p_lUserId,
                                                            string p_directoryPath, MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo(
                "---GetImageFromFullPathByUserId-----p_lstImageFullPath.Count[" + p_lstImageFullPath.Count +
                "]--------------");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            var l_oLstImageRio = new List<ImageRio>();
            ImageRio l_oImageRio;
            try
            {
                var l_iCpt = 0;
                foreach (var l_sFileNameFullPath in p_lstImageFullPath)
                {
                    if (File.Exists(l_sFileNameFullPath))
                    {
                        var l_oFi = new FileInfo(l_sFileNameFullPath);
                        var l_bFileTransfered = false;
                        FileStream l_oFileStream = null;
                        // We must loop until the file is completely transfered by the webservice because the FileSystemWatcher fires the event as soon
                        // as a new file ( even not complete ) is created in the directory.
                        while (!l_bFileTransfered)
                        {
                            try
                            {
                                using (File.OpenRead(l_oFi.FullName))
                                {
                                    l_oFileStream = new FileStream(l_oFi.FullName, FileMode.Open, FileAccess.Read,
                                                                   FileShare.ReadWrite);
                                    l_bFileTransfered = true;
                                }
                            }
                                // Catch to wait until file is completely transfered in the directory
                            catch
                            {
                            }
                        }

                        // get file length
                        var l_iLength = (int) l_oFileStream.Length;
                        // create buffer
                        var l_oBuffer = new byte[l_iLength];
                        // actual number of bytes read
                        int l_iCount;
                        // total number of bytes read
                        var sum = 0;

                        // read until Read method returns 0 (end of the stream has been reached)
                        while ((l_iCount = l_oFileStream.Read(l_oBuffer, sum, l_iLength - sum)) > 0)
                            sum += l_iCount; // sum is a buffer offset for next reading

                        l_oFileStream.Dispose();
                        l_oFileStream.Close();

                        //Add path if exist
                        if (!string.IsNullOrEmpty(p_directoryPath))
                        {
                            l_oImageRio = new ImageRio(Path.Combine(p_directoryPath, l_oFi.Name), l_oBuffer,
                                                       l_oFi.Length);
                            l_oImageRio.RootDirectoryName = p_directoryPath;
                        }
                        else
                        {
                            l_oImageRio = new ImageRio(l_oFi.Name, l_oBuffer, l_oFi.Length);
                        }


                        FileInfo l_oFileInfoOriginalFile;
                        if (p_lstOriginalImageFullPath == null)
                        {
                            if (string.IsNullOrEmpty(p_directoryPath))
                            {
                                l_oFileInfoOriginalFile =
                                    new FileInfo(
                                        GetImportDocumentFullPath(Path.GetFileNameWithoutExtension(l_oFi.FullName),
                                                                  p_lUserId));
                            }
                            else
                            {
                                //string DirectoryRoot = Path.GetFileNameWithoutExtension(l_oFi.FullName);
                                l_oFileInfoOriginalFile =
                                    new FileInfo(
                                        GetImportDocumentFullPath(Path.GetFileNameWithoutExtension(l_oFi.FullName),
                                                                  p_lUserId,
                                                                  Path.GetFileNameWithoutExtension(p_directoryPath)));
                            }
                        }
                        else
                        {
                            l_oFileInfoOriginalFile =
                                new FileInfo(p_lstOriginalImageFullPath[l_iCpt]);
                        }

                        l_oImageRio.NumberPages = GetNumberOfPageInDocument(l_oFileInfoOriginalFile);

                        if (l_oFileInfoOriginalFile.Exists)
                            Treatments.FillMetadata(l_oFileInfoOriginalFile, ref l_oImageRio, EnableMetaData);

                        l_oLstImageRio.Add(l_oImageRio);
                        l_oBuffer = null;
                    }
                    else
                    {
                        l_oImageRio =
                            new ImageRio("------- EXCEPTION IN WCF GetImageFromFullPathByUserId. The file [" +
                                         l_sFileNameFullPath + "] does not exists-----------------");
                        LogManager.Instance().LogError(l_oImageRio.FullErrorMessage);
                    }
                    l_iCpt++;
                }
            }
            catch (Exception ex)
            {
                l_oImageRio =
                    new ImageRio(
                        "------------- EXCEPTION IN WCF GetImageFromFullPathByUserId EXCEPTION[" + DateTime.Now + "]",
                        new Exception(ex.Message));
                LogManager.Instance().LogError(l_oImageRio.FullErrorMessage);
                l_oLstImageRio.Add(l_oImageRio);
            }

            LogManager.Instance().LogInfo("---------------------------------[" + l_oLstImageRio.Count +
                                          "] thumb found--------------" + DateTime.Now);
            LogManager.Instance().LogInfo("---GetImageFromFullPathByUserId-----------------");
            LogManager.Instance().LogInfo("END OF WCF SERVICE CALL ---------------------");

            return l_oLstImageRio;
        }

        /// <summary>
        ///   Retrieve document fullpath
        /// </summary>
        /// <param name="p_sDocumentName"> Document Name </param>
        /// <param name="p_lUserId"> User Identifier </param>
        /// <returns> The full path of the file </returns>
        private string GetImportDocumentFullPath(string p_sDocumentName, long p_lUserId)
        {
            return Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.InputDirectory"),
                                p_lUserId + "\\" + p_sDocumentName);
        }

        /// <summary>
        ///   Retrieve document fullpath
        /// </summary>
        /// <param name="p_sDocumentName"> Document Name </param>
        /// <param name="p_lUserId"> User Identifier </param>
        /// <param name="p_sDirectoryPath"> Path to combine </param>
        /// <returns> The full path of the file </returns>
        private string GetImportDocumentFullPath(string p_sDocumentName, long p_lUserId, string p_sDirectoryPath)
        {
            string l_sPath = ConfigurationManager.AppSettings.Get("Rio.WCF.Services.InputDirectory") + "\\" +
                             p_lUserId;
            if (!string.IsNullOrEmpty(p_sDirectoryPath))
            {
                l_sPath += "\\" + p_sDirectoryPath;
            }
            l_sPath += "\\" + p_sDocumentName;
            return l_sPath;
        }

        /// <summary>
        ///   Get the number of page in a document
        /// </summary>
        /// <param name="p_oFileInfo"> The p_o file info. </param>
        /// <param name="overwritePageCountSettingParameter"> if set to <c>true</c> [overwrite setting parameter]. </param>
        /// <returns> </returns>
        private int GetNumberOfPageInDocument(FileInfo p_oFileInfo, bool overwritePageCountSettingParameter = false)
        {
            var l_iNumberOfPages = 0;
            try
            {
                if (p_oFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.PPT.szGetDescription()))
                {
                    var l_oPresentation = new Presentation(p_oFileInfo.FullName);
                    l_iNumberOfPages = l_oPresentation.Slides.Count;
                    l_oPresentation = null;
                }
                else if (p_oFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.PDF.szGetDescription()))
                {
                    // we create a reader for a the specified document
                    PdfReader l_oReader = null;
                    try
                    {
                        l_oReader = new PdfReader(p_oFileInfo.FullName);
                        l_iNumberOfPages = l_oReader.NumberOfPages;
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                    finally
                    {
                        if (l_oReader != null)
                            l_oReader.Close();
                    }
                }
                else if (p_oFileInfo.Extension.ToLower().Equals(Constant.ImageFileFormat.TIF.szGetDescription())
                         || p_oFileInfo.Extension.ToLower().Equals(Constant.ImageFileFormat.TIFF.szGetDescription()))
                {
                    if (overwritePageCountSettingParameter || EnabledPageCount)
                    {
                        using (Image image = Image.FromFile(p_oFileInfo.FullName))
                        {
                            l_iNumberOfPages = image.GetFrameCount(FrameDimension.Page);
                            image.Dispose();
                        }
                    }
                }
                else if (p_oFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.XLSX.szGetDescription())
                         || p_oFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.XLS.szGetDescription())
                    )
                {
                    #region Aspose licencing

                    var xlsLicense = new Aspose.Cells.License();
                    xlsLicense.SetLicense("Aspose.Total.lic");

                    #endregion

                    var l_oWorkbook = new Workbook(p_oFileInfo.FullName);

                    //Open template
                    var l_oImgOptions = new ImageOrPrintOptions
                                            {
                                                ImageFormat = ImageFormat.Jpeg,
                                                IsImageFitToPage = true,
                                            };

                    for (var i = 0; i < l_oWorkbook.Worksheets.Count; i++)
                    {
                        var sheet = l_oWorkbook.Worksheets[i];
                        //To remove the white border around the image.
                        //Hide the sheet gridlines
                        sheet.IsGridlinesVisible = true;

                        //Setting the orientation to Landscape
                        sheet.PageSetup.Orientation = PageOrientationType.Landscape;

                        //Setting the paper size Tabloid
                        sheet.PageSetup.PaperSize = PaperSizeType.PaperTabloid;

                        //Setting the print quality of the worksheet to 1200 dpi
                        sheet.PageSetup.PrintQuality = 1200;

                        var sheetRender = new SheetRender(sheet, l_oImgOptions);
                        l_iNumberOfPages = l_iNumberOfPages + sheetRender.PageCount;
                    }
                }
                else if (p_oFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.DOC.szGetDescription())
                         || p_oFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.DOCX.szGetDescription())
                         || p_oFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.RTF.szGetDescription())
                    )
                {
                    var l_oWordDocument = new Aspose.Words.Document(p_oFileInfo.FullName);
                    l_iNumberOfPages = l_oWordDocument.PageCount;
                    l_oWordDocument = null;
                }
            }
            catch (Exception ex)
            {
                LogManager.Instance().LogError("GetNumberOfPageInDocument [" + ex.Message + "]");
            }

            return l_iNumberOfPages;
        }

        /// <summary>
        ///   Get the optimal size of the image
        /// </summary>
        /// <param name="p_iActuelWidth"> The actual size of the image </param>
        /// <param name="p_iActuelHeigth"> The actual heigth of the image </param>
        /// <param name="p_iMax"> The maximum heigth or width accepted </param>
        /// <returns> The new optimal size </returns>
        private Size GetSizeImage(int p_iActuelWidth, int p_iActuelHeigth, int p_iMax)
        {
            var l_oSize = new Size(p_iActuelWidth, p_iActuelHeigth);

            if (p_iActuelWidth > p_iActuelHeigth)
            {
                var l_iRatio = float.Parse(p_iActuelWidth.ToString())/float.Parse(p_iActuelHeigth.ToString());
                var l_iNewWidth = p_iMax*l_iRatio;

                l_oSize.Height = p_iMax;
                l_oSize.Width = Convert.ToInt32(l_iNewWidth);
            }
            else
            {
                var l_iRatio = float.Parse(p_iActuelHeigth.ToString())/float.Parse(p_iActuelWidth.ToString());
                var l_iNewHeigth = p_iMax*l_iRatio;

                l_oSize.Width = p_iMax;
                l_oSize.Height = Convert.ToInt32(l_iNewHeigth);
            }

            return l_oSize;
        }

        /// <summary>
        ///   Retrieve document thumbnail fullpath
        /// </summary>
        /// <param name="p_sDocumentName"> Document Name </param>
        /// <param name="p_lUserId"> User Identifier </param>
        /// <returns> The full path of the thumbnail file </returns>
        private string GetThumbDocumentFullPath(string p_sDocumentName, long p_lUserId)
        {
            return Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.OutputDirectory"),
                                p_lUserId + "\\" + p_sDocumentName + Constant.ImageFileFormat.JPG.szGetDescription());
        }

        /// <summary>
        /// </summary>
        /// <param name="p_sDocumentName"> </param>
        /// <param name="p_lUserId"> </param>
        /// <param name="p_sDirectoryPath"> </param>
        /// <returns> </returns>
        private string GetThumbDocumentFullPath(string p_sDocumentName, long p_lUserId, string p_sDirectoryPath)
        {
            string l_sPath = ConfigurationManager.AppSettings.Get("Rio.WCF.Services.OutputDirectory") + "\\" +
                             p_lUserId;
            if (!string.IsNullOrEmpty(p_sDirectoryPath))
            {
                l_sPath += "\\" + p_sDirectoryPath;
            }
            if (!string.IsNullOrEmpty(p_sDocumentName))
            {
                l_sPath += "\\" + p_sDocumentName + Constant.ImageFileFormat.JPG.szGetDescription();
            }
            return l_sPath;
        }

        /// <summary>
        /// </summary>
        /// <param name="p_lFileInfo"> </param>
        /// <param name="p_iMaxWeigthInKo"> </param>
        /// <returns> </returns>
        private bool IsFileTooLarge(FileInfo p_lFileInfo, int p_iMaxWeigthInKo)
        {
            return p_lFileInfo.Length > p_iMaxWeigthInKo;
        }

        /// <summary>
        ///   Joinf file
        /// </summary>
        /// <param name="p_sFolderInputPath"> Folder where all the part of the files are </param>
        /// <param name="p_oFileOutputPath"> The output Filestream </param>
        private void JoinFiles(string p_sFolderInputPath, FileStream p_oFileOutputPath)
        {
            // Needed to get all files in that directory
            var l_oDiSource = new DirectoryInfo(p_sFolderInputPath);
            var l_oRgFiles = l_oDiSource.GetFiles("*.*");
            var l_oOrderedFiles = l_oRgFiles.OrderBy(f => f.Name);

            // Filestream to reconstruct the file
            var l_oFsSource = p_oFileOutputPath;

            // Loop through all the files with the *.part extension in the folder
            foreach (var fiPart in l_oOrderedFiles)
            {
                // Create a byte array of the content of the current file
                var l_oBytePart = File.ReadAllBytes(fiPart.FullName);
                // Write the bytes to the reconstructed file
                l_oFsSource.Write(l_oBytePart, 0, l_oBytePart.Length);
            }

            // Close the file stream
            l_oFsSource.Close();
        }

        /// <summary>
        ///   Set GdPicture Licence key
        /// </summary>
        private void LicenseGdPicture()
        {
            m_oGdPictureImaging.SetLicenseNumberUpgrade(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.GdPicture.License.V7"),
                                                        ConfigurationManager.AppSettings.Get("Rio.WCF.Services.GdPicture.License.V8"));
            m_oGdPictureImaging.SetLicenseNumberOCRTesseract(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.GdPicture.License.V8"));
            m_oGdPicturePDF.SetLicenseNumber(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.GdPicture.License.V8"));
        }

        /// <summary>
        ///   Allow the user to Merge multiple image in a single PDF
        /// </summary>
        /// <param name="p_lstDocumentFullPath"> List of all Rio images to merge </param>
        /// <param name="p_sDestinationFileFullPath"> The P_S destination file full path. </param>
        /// <param name="p_oMessageRequest"> The p_o message request. </param>
        /// <returns> True if success </returns>
        private ReturnString MergeDocumentFullPathInPdf(string p_lstDocumentFullPath, string p_sDestinationFileFullPath,
                                                        MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---MergeDocumentFullPathInPdf-----p_lstDocument[" +
                                          p_lstDocumentFullPath + "]");

            var l_oReturnString = new ReturnString {IsValid = true};
            var l_otempDir = Treatments.CreateTemporaryDirectory();
            try
            {
                //Temporary directory

                #region Aspose Licencing

                var pdfLicence = new Aspose.Pdf.License();
                pdfLicence.SetLicense("Aspose.Total.lic");

                #endregion

                //Pdf for images
                Section l_oSection;
                Text l_oText;

                //We add all documents to the list that will be merge in the pdf file
                LogManager.Instance().LogInfo("------------------------------  Processing Document [" +
                                              p_lstDocumentFullPath + "]");

                var l_sFileExtension = new FileInfo(p_lstDocumentFullPath).Extension.ToLower();

                if (l_sFileExtension.Equals(Constant.ImageFileFormat.JPEG.szGetDescription())
                    || l_sFileExtension.Equals(Constant.ImageFileFormat.JPG.szGetDescription()))
                {
                    #region Jpeg

                    //Adding a new section to the pdf file
                    var l_oPdf = new Pdf();
                    l_oSection = l_oPdf.Sections.Add();
                    l_oText = new Text(string.Empty);
                    l_oSection.Paragraphs.Add(l_oText);
                    l_oText.IsFirstParagraph = true;

                    try
                    {
                        LicenseGdPicture();
                        string tempPath = Path.Combine(l_otempDir,
                                                       Path.GetFileName(p_lstDocumentFullPath) +
                                                       Constant.ImageFileFormat.JPG.szGetDescription());
                        int m_iImageID = m_oGdPictureImaging.CreateGdPictureImageFromFile(p_lstDocumentFullPath);
                        m_oGdPictureImaging.SaveAsJPEG(m_iImageID, tempPath);
                        m_oGdPictureImaging.ReleaseGdPictureImage(m_iImageID);
                        l_oSection.BackgroundImageFile = tempPath;

                        l_oPdf.Save(p_sDestinationFileFullPath);
                    }
                    catch
                    {
                        l_oPdf.Close();
                        l_oPdf = null;
                        var l_oImageTemp = Image.FromFile(p_lstDocumentFullPath);
                        l_oImageTemp.Save(Path.Combine(l_otempDir,
                                                       Path.GetFileName(p_lstDocumentFullPath) +
                                                       Constant.ImageFileFormat.TIF.szGetDescription()));

                        l_oSection.BackgroundImageFile = Path.Combine(l_otempDir,
                                                                      Path.GetFileName(p_lstDocumentFullPath) +
                                                                      Constant.ImageFileFormat.TIF.szGetDescription());

                        l_oPdf.Save(p_sDestinationFileFullPath);
                        l_oImageTemp.Dispose();
                    }

                    #endregion
                }
                else if (l_sFileExtension.Equals(Constant.ImageFileFormat.TIF.szGetDescription())
                         || l_sFileExtension.Equals(Constant.ImageFileFormat.TIFF.szGetDescription()))
                {
                    #region Tiff / Tif

                    //Adding a new section to the pdf file
                    var l_oPdf = new Pdf();
                    LogManager.Instance().LogInfo("--------------MergeDocumentInPDF----------------  ");
                    var l_sImageFullPathIfException = string.Empty;

                    var l_lstSplitedFiles = string.Empty;
                    LogManager.Instance().LogInfo(
                        "--------------MergeDocumentInPDF----------------  Checking pdf number of pages");
                    if (GetNumberOfPageInDocument(new FileInfo(p_lstDocumentFullPath), true) > 1)
                    {
                        LogManager.Instance().LogInfo(
                            "--------------MergeDocumentInPDF----------------  one page file");
                        l_lstSplitedFiles = SplitFiles(new FileInfo(p_lstDocumentFullPath));
                        var l_oDi = new DirectoryInfo(l_lstSplitedFiles);
                        var l_oRgFiles = l_oDi.GetFiles("*.*");
                        var l_oOrderedFiles = l_oRgFiles.OrderBy(f => f.Name);

                        foreach (var l_oFileInfo in l_oOrderedFiles)
                        {
                            l_oSection = l_oPdf.Sections.Add();
                            l_oText = new Text(string.Empty);
                            l_oSection.Paragraphs.Add(l_oText);
                            l_oText.IsFirstParagraph = true;
                            l_oSection.BackgroundImageFile = l_oFileInfo.FullName;
                            LogManager.Instance().LogInfo(
                                "--------------MergeDocumentInPDF----------------  Adding image in pdf document [" +
                                l_oFileInfo.FullName + "] ");
                        }
                    }
                    else
                    {
                        LogManager.Instance().LogInfo(
                            "--------------MergeDocumentInPDF----------------  Multiple page file");
                        l_oSection = l_oPdf.Sections.Add();
                        l_oText = new Text(string.Empty);
                        l_oSection.Paragraphs.Add(l_oText);
                        l_oText.IsFirstParagraph = true;

                        LogManager.Instance().LogInfo(
                            "--------------MergeDocumentInPDF----------------  converting image before dding in aspose [" +
                            p_lstDocumentFullPath + "] ");
                        l_sImageFullPathIfException = Treatments.CreateTemporaryDirectory();
                        l_sImageFullPathIfException = Path.Combine(l_sImageFullPathIfException, "output.jpg");

                        LicenseGdPicture();
                        int m_iImageID = m_oGdPictureImaging.CreateGdPictureImageFromFile(p_lstDocumentFullPath);
                        //m_oGdPictureImaging.TiffSelectPage(m_iImageID, p_iStartPage);
                        m_iHeigth = m_oGdPictureImaging.GetHeight(m_iImageID);
                        m_iWidth = m_oGdPictureImaging.GetWidth(m_iImageID);
                        m_oGdPictureImaging.SaveAsJPEG(m_iImageID, l_sImageFullPathIfException);
                        m_oGdPictureImaging.ReleaseGdPictureImage(m_iImageID);
                        //m_oGdPictureImaging.ClearGdPicture();

                        l_oSection.BackgroundImageFile = l_sImageFullPathIfException;
                    }

                    l_oPdf.Save(p_sDestinationFileFullPath);

                    LogManager.Instance().LogInfo(
                        "---------------MergeDocumentInPDF---------------  deleteing directory [" + l_lstSplitedFiles +
                        "] ");

                    if (l_lstSplitedFiles != string.Empty)
                        Treatments.DeleteDirectory(l_lstSplitedFiles);

                    if (l_sImageFullPathIfException != string.Empty)
                        Treatments.DeleteDirectory(Path.GetDirectoryName(l_sImageFullPathIfException));

                    #endregion
                }
                else if (l_sFileExtension.Equals(Constant.ImageFileFormat.BMP.szGetDescription())
                         || l_sFileExtension.Equals(Constant.ImageFileFormat.PNG.szGetDescription())
                         || l_sFileExtension.Equals(Constant.ImageFileFormat.GIF.szGetDescription()))
                {
                    #region Other images extension

                    //Adding a new section to the pdf file
                    var l_oPdf = new Pdf();

                    l_oSection = l_oPdf.Sections.Add();
                    l_oText = new Text(string.Empty);
                    l_oSection.Paragraphs.Add(l_oText);
                    l_oText.IsFirstParagraph = true;

                    l_oSection.BackgroundImageFile = p_lstDocumentFullPath;

                    l_oPdf.Save(p_sDestinationFileFullPath);

                    #endregion
                }
                else
                {
                    if (l_sFileExtension.Equals(Constant.DocumentFileFormat.DOC.szGetDescription())
                        || l_sFileExtension.Equals(Constant.DocumentFileFormat.DOCX.szGetDescription())
                        || l_sFileExtension.Equals(Constant.DocumentFileFormat.RTF.szGetDescription())
                        )
                    {
                        #region Word

                        ConvertWordToPdf(p_lstDocumentFullPath, p_sDestinationFileFullPath);

                        #endregion
                    }
                    else if (l_sFileExtension.Equals(Constant.DocumentFileFormat.TXT.szGetDescription()))
                    {
                        #region TXT

                        ConvertTextToPdf(p_lstDocumentFullPath, p_sDestinationFileFullPath);

                        #endregion
                    }
                    else if (l_sFileExtension.Equals(Constant.DocumentFileFormat.XLS.szGetDescription())
                             || l_sFileExtension.Equals(Constant.DocumentFileFormat.XLSX.szGetDescription()))
                    {
                        #region XLS

                        ConvertXlsToPdf(p_lstDocumentFullPath, p_sDestinationFileFullPath);

                        #endregion
                    }
                    else if (l_sFileExtension.Equals(Constant.DocumentFileFormat.PDF.szGetDescription()))
                    {
                        #region PDF

                        File.Copy(p_lstDocumentFullPath, p_sDestinationFileFullPath, true);

                        #endregion
                    }
                    else if (l_sFileExtension.Equals(Constant.DocumentFileFormat.PPT.szGetDescription()))
                    {
                        #region PPT

                        ConvertPowerpointToPdf(p_lstDocumentFullPath, p_sDestinationFileFullPath);

                        #endregion
                    }
                    else if (l_sFileExtension.Equals(Constant.DocumentFileFormat.PPTX.szGetDescription()))
                    {
                        #region PPTX

                        ConvertPowerpointXToPdf(p_lstDocumentFullPath, p_sDestinationFileFullPath);

                        #endregion
                    }
                    else
                    {
                        LogManager.Instance().LogError("------------- File format not supported : [" +
                                                       p_lstDocumentFullPath +
                                                       "]. The file will not be added to the merged document." +
                                                       DateTime.Now);
                    }
                }

                l_oReturnString.Value = p_sDestinationFileFullPath;
                Treatments.DeleteDirectory(l_otempDir);
            }
            catch (Exception ex)
            {
                if (!l_otempDir.Equals(string.Empty) && Directory.Exists(l_otempDir))
                    Treatments.DeleteDirectory(l_otempDir);
                l_oReturnString =
                    new ReturnString(
                        "------------- EXCEPTION IN WCF MergeDocumentFullPathInPdf EXCEPTION[" + DateTime.Now + "]",
                        new Exception(ex.Message));
                l_oReturnString.ErrorCode = (int) ReturnObject.ErrorCodes.MergeFileDuringImportError;
                LogManager.Instance().LogError(l_oReturnString.FullErrorMessage);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---MergeDocumentFullPathInPdf-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return l_oReturnString;
        }

        /// <summary>
        ///   Allow to merge Pdf files
        /// </summary>
        /// <param name="p_sDestinationFileFullPath"> The path of the final pdf merged file </param>
        /// <param name="p_lstSourceFilesFullPath"> All pdf file to merge </param>
        private void MergePdfFiles(string p_sDestinationFileFullPath, List<string> p_lstSourceFilesFullPath)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---------------------------Call of MergePdfFiles");

            try
            {
                var l_oPdfReader = new PdfReader(p_lstSourceFilesFullPath[0]);

                var l_oDocument = new iTextSharp.text.Document(l_oPdfReader.GetPageSizeWithRotation(1));
                l_oDocument.AddTitle(Path.GetFileName(p_sDestinationFileFullPath));
                l_oDocument.AddSubject("Créé par RIO5");
                l_oDocument.AddCreator("RIO5");
                l_oDocument.AddHeader(Path.GetFileName(p_sDestinationFileFullPath), String.Empty);

                var l_oPdfCpy = new PdfCopy(l_oDocument,
                                            new FileStream(p_sDestinationFileFullPath, FileMode.Create,
                                                           FileAccess.ReadWrite, FileShare.ReadWrite));
                l_oDocument.Open();

                for (int i = 1; i <= p_lstSourceFilesFullPath.Count; i++)
                {
                    for (var j = 1; j <= l_oPdfReader.NumberOfPages; j++)
                    {
                        var l_oPage = l_oPdfCpy.GetImportedPage(l_oPdfReader, j);
                        l_oPdfCpy.AddPage(l_oPage);
                        //l_oDocument.Close();
                    }
                    if (i < p_lstSourceFilesFullPath.Count)
                    {
                        l_oPdfReader = new PdfReader(p_lstSourceFilesFullPath[i]);
                        //l_oDocument = new iTextSharp.text.Document(l_oPdfReader.GetPageSizeWithRotation(1));
                    }
                }

                l_oPdfCpy.Close();
                l_oDocument.Close();
            }
            catch (Exception e)
            {
                LogManager.Instance().LogError(
                    "-------------------------------------- Exception in MergePdfFiles. Exception[" + e.StackTrace + "]");
            }
        }

        /// <summary>
        ///   The files to split
        /// </summary>
        /// <param name="p_oFileSystemInfo"> the full path of the file to split </param>
        private string SplitFiles(FileSystemInfo p_oFileSystemInfo)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---------------------------Call of SplitFiles");

            if (!p_oFileSystemInfo.Exists)
                throw new FileNotFoundException(" Exception in SplitFiles. File not Found : [" +
                                                p_oFileSystemInfo.FullName + "]");

            var l_sTemporaryDirectory = Treatments.CreateTemporaryDirectory();

            try
            {
                var l_oTiffManager = new TiffManager(p_oFileSystemInfo.FullName)
                                         {TempWorkingDir = l_sTemporaryDirectory};
                l_oTiffManager.SplitTiffImage(l_sTemporaryDirectory, EncoderValue.CompressionLZW);
            }
            catch (Exception ex)
            {
                LogManager.Instance().LogError(
                    "-------------------------------------- Exception in SplitFiles. Exception[" + ex.StackTrace + "]");
            }

            LogManager.Instance().LogInfo("---------------------------End of Call of SplitFiles");

            return l_sTemporaryDirectory;
        }

        /// <summary>
        ///   Convert a Stream to a byte array
        /// </summary>
        /// <param name="l_oStream"> the stream to convert </param>
        /// <returns> The converted byte array </returns>
        private byte[] StreamtoByteArray(Stream l_oStream)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---------------------------Call of StreamtoByteArray");

            if (l_oStream == null)
                throw new ArgumentNullException("l_oStream");
            var l_iOffset = 0;
            var l_oRemaining = (int) l_oStream.Length;
            var l_oData = new byte[l_oRemaining];
            while (l_oRemaining > 0)
            {
                var l_oRead = l_oStream.Read(l_oData, l_iOffset, l_oRemaining);
                if (l_oRead <= 0)
                    throw new EndOfStreamException();
                l_oRemaining -= l_oRead;
                l_iOffset += l_oRead;
            }
            LogManager.Instance().LogInfo("---------------------------End of Call of StreamtoByteArray");

            return l_oData;
        }

        #endregion

        #region IWCFService Members

        /// <summary>
        ///   Prepare a folder for the extraction
        /// </summary>
        /// <param name="p_oGuid"> Identifier of the extraction </param>
        /// <param name="p_oMessageRequest"> Security Object </param>
        /// <returns> True if success </returns>
        public ReturnBoolean DeleteExtractFolder(Guid p_oGuid, MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---DeleteExtractFolder----- p_oGuid[" + p_oGuid + "]");
            var l_oReturnBoolean = new ReturnBoolean {Value = true};

            try
            {
                Treatments.CheckApplicationRequestKey(p_oMessageRequest);

                //Checking extraction working directory
                DirectoryInfo l_oFolderDirectory =
                    new DirectoryInfo(
                        Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.FolderExtraction"),
                                     p_oGuid.ToString()));
                Treatments.DeleteDirectory(l_oFolderDirectory.FullName);
            }
            catch (Exception ex)
            {
                l_oReturnBoolean =
                    new ReturnBoolean(
                        "------------- EXCEPTION IN WCF DeleteExtractFolder EXCEPTION[" + DateTime.Now + "]",
                        new Exception(ex.Message));
                LogManager.Instance().LogError(l_oReturnBoolean.FullErrorMessage);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---DeleteExtractFolder-----------------");
            LogManager.Instance().LogInfo("END OF WCF SERVICE CALL ---------------------");

            return l_oReturnBoolean;
        }

        /// <summary>
        ///   Prepare a folder for the extraction
        /// </summary>
        /// <param name="p_oGuid"> Identifier of the extraction </param>
        /// <param name="p_iFolderId"> The Foilder Identifier </param>
        /// <param name="p_sFolderName"> Name of the P_S folder. </param>
        /// <param name="p_dicFolderIndex"> The index valorization of the folder </param>
        /// <param name="p_dicFilePathItem"> The fullpath of the file and it's item localization </param>
        /// <param name="p_oMessageRequest"> Security Object </param>
        /// <returns> True if success </returns>
        public ReturnBoolean ExtractFolder(Guid p_oGuid, long p_iFolderId, string p_sFolderName,
                                           Dictionary<string, string> p_dicFolderIndex,
                                           Dictionary<string, string> p_dicFilePathItem,
                                           MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---ExtractFolder----- p_oGuid[" + p_oGuid + "]");
            var l_oReturnBoolean = new ReturnBoolean {Value = true};

            try
            {
                Treatments.CheckApplicationRequestKey(p_oMessageRequest);

                //Checking extraction working directory
                DirectoryInfo l_oFolderDirectory =
                    new DirectoryInfo(
                        Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.FolderExtraction"),
                                     Path.Combine(p_oGuid.ToString(), p_sFolderName)));
                Treatments.CheckDirectory(l_oFolderDirectory.FullName);

                //  Creating the index file
                StreamWriter l_oFIndexFile =
                    new StreamWriter(Path.Combine(l_oFolderDirectory.FullName, p_sFolderName + ".index"));
                foreach (string m_sKey in p_dicFolderIndex.Keys)
                {
                    l_oFIndexFile.WriteLine(m_sKey + ";" + p_dicFolderIndex[m_sKey]);
                }


                l_oFIndexFile.Dispose();
                l_oFIndexFile.Close();
                l_oFIndexFile = null;

                //    Preparing the files
                string l_sOriginalFileName = string.Empty;
                string l_sIndexedFileName = string.Empty;

                foreach (string m_sKey in p_dicFilePathItem.Keys)
                {
                    l_sIndexedFileName = ((m_sKey.Split('#')))[0];
                    l_sOriginalFileName = ((m_sKey.Split('#')))[1];

                    //Creating the folder of the file
                    Treatments.CheckDirectory(Path.Combine(l_oFolderDirectory.FullName, p_dicFilePathItem[m_sKey]));
                    File.Copy(l_sIndexedFileName,
                              Path.Combine(Path.Combine(l_oFolderDirectory.FullName, p_dicFilePathItem[m_sKey]),
                                           l_sOriginalFileName));
                }
            }
            catch (Exception ex)
            {
                l_oReturnBoolean =
                    new ReturnBoolean("------------- EXCEPTION IN WCF ExtractFolder EXCEPTION[" + DateTime.Now + "]",
                                      new Exception(ex.Message));
                LogManager.Instance().LogError(l_oReturnBoolean.FullErrorMessage);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---ExtractFolder-----------------");
            LogManager.Instance().LogInfo("END OF WCF SERVICE CALL ---------------------");

            return l_oReturnBoolean;
        }

        /// <summary>
        ///   Retrieving the extracted folders
        /// </summary>
        /// <param name="p_oGuid"> Identifier of the extraction </param>
        /// <param name="p_oMessageRequest"> Security Object </param>
        /// <returns> The zipped file if success </returns>
        public ReturnDoubleValue GetExtractedFolders(Guid p_oGuid, MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---GetExtractedFolders----- p_oGuid[" + p_oGuid + "]");
            var l_oReturnDoubleValue = new ReturnDoubleValue {Value = null};
            ZipOutputStream l_oZipStream = null;
            DirectoryInfo l_oDirectoryInfo =
                new DirectoryInfo(Path.Combine(
                    ConfigurationManager.AppSettings.Get("Rio.WCF.Services.FolderExtraction"),
                    Path.Combine(p_oGuid.ToString())));

            try
            {
                Treatments.CheckApplicationRequestKey(p_oMessageRequest);

                // generate file list
                ArrayList l_oAllFilesToCompress = GenerateFileList(l_oDirectoryInfo.FullName);

                int l_iTrimLength = (l_oDirectoryInfo.FullName).Length;
                // find number of chars to remove     
                // from orginal file path
                l_iTrimLength += 1; //remove '\'
                FileStream l_oostream = null;
                byte[] l_obuffer;
                string l_sOutPath = l_oDirectoryInfo.FullName + @"\" + "zipped.zip";
                l_oZipStream = new ZipOutputStream(File.Create(l_sOutPath)); // create zip stream

                l_oZipStream.SetLevel(int.Parse(ConfigurationManager.AppSettings.Get("ZipCompression"))); // compression
                ZipEntry l_oZipEntry;
                foreach (string l_sFil in l_oAllFilesToCompress) // for each file, generate a zipentry
                {
                    l_oZipEntry = new ZipEntry(l_sFil.Remove(0, l_iTrimLength));
                    l_oZipStream.PutNextEntry(l_oZipEntry);

                    if (!l_sFil.EndsWith(@"/")) // if a file ends with '/' its a directory
                    {
                        l_oostream = File.OpenRead(l_sFil);
                        l_obuffer = new byte[l_oostream.Length];
                        l_oostream.Read(l_obuffer, 0, l_obuffer.Length);
                        l_oZipStream.Write(l_obuffer, 0, l_obuffer.Length);
                    }
                }

                l_obuffer = null;

                l_oZipEntry = null;

                if (l_oostream != null)
                {
                    l_oostream.Close();
                    l_oostream.Dispose();
                }

                l_oZipStream.Finish();
                l_oZipStream.Close();
                l_oZipStream.Dispose();
                l_oZipStream = null;

                FileStream fs = new FileStream(l_sOutPath, FileMode.Open);
                byte[] binary = StreamtoByteArray(fs);
                fs.Close();
                fs.Dispose();
                fs = null;


                l_oReturnDoubleValue.Value = binary;
                binary = null;


                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            catch (Exception ex)
            {
                l_oReturnDoubleValue =
                    new ReturnDoubleValue(
                        "------------- EXCEPTION IN WCF GetExtractedFolders EXCEPTION[" + DateTime.Now + "]",
                        new Exception(ex.Message));
                LogManager.Instance().LogError(l_oReturnDoubleValue.FullErrorMessage);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---GetExtractedFolders-----------------");
            LogManager.Instance().LogInfo("END OF WCF SERVICE CALL ---------------------");

            return l_oReturnDoubleValue;
        }

        /// <summary>
        ///   Generates the report.
        /// </summary>
        /// <param name="p_lUserId"> User Identifier </param>
        /// <param name="p_sXmlSourceDocumentName"> Xml document name </param>
        /// <param name="p_sReportDestinationFullPath"> Destination of the generated report </param>
        /// <param name="p_sUserEmailAdress"> The P_S user email adress. </param>
        /// <param name="p_oMessageRequest"> Security object </param>
        public void GenerateReport(long p_lUserId, string p_sXmlSourceDocumentName, string p_sReportDestinationFullPath,
                                   string p_sUserEmailAdress, MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---GenerateReport----- p_lUserId[" + p_lUserId +
                                          "]p_sXmlSourceDocumentName[" + p_sXmlSourceDocumentName +
                                          "]p_sReportDestinationFullPath[" +
                                          p_sReportDestinationFullPath + "]");

            try
            {
                Treatments.CheckApplicationRequestKey(p_oMessageRequest);

                if (!Directory.Exists(Path.GetDirectoryName(p_sReportDestinationFullPath)))
                    Treatments.CheckDirectory(Path.GetDirectoryName(p_sReportDestinationFullPath));

                var l_sXmlDataFileFullPath = GetImportDocumentFullPath(p_sXmlSourceDocumentName, p_lUserId);
                if (!File.Exists(l_sXmlDataFileFullPath))
                    throw new Exception("------------- EXCEPTION IN WCF GenerateReport send mail EXCEPTION[" +
                                        DateTime.Now + "] Message [File " + l_sXmlDataFileFullPath + " does not exists]");

                #region Initialisation

                var l_sWorkingDirectory = Treatments.CreateTemporaryDirectory();
                Treatments.CheckDirectory(l_sWorkingDirectory);

                var m_oExporParameter = new ReportParameter();

                var l_oItextSharpPageEventhandler = new ReportHandler();

                PdfPCell l_oCellFolder = null;

                var l_oXmlDocument = new XmlDocument();
                l_oXmlDocument.Load(l_sXmlDataFileFullPath);

                var l_oItextSharpDocument = new iTextSharp.text.Document(PageSize.A4, 36, 36, 54, 36);
                var l_oItextSharpWriter = PdfWriter.GetInstance(l_oItextSharpDocument,
                                                                new FileStream(
                                                                    p_sReportDestinationFullPath,
                                                                    FileMode.Create));
                l_oItextSharpWriter.PageEvent = l_oItextSharpPageEventhandler;
                l_oItextSharpDocument.Open();
                l_oItextSharpWriter.SetLinearPageMode();
                l_oItextSharpWriter.SetPdfVersion(PdfWriter.PDF_VERSION_1_7);
                l_oItextSharpWriter.CompressionLevel = PdfStream.BEST_SPEED;

                #endregion

                #region Contenu

                l_oItextSharpPageEventhandler.m_sHeaderTitle = m_oExporParameter.ExportInventaireBiensHeaderPageText;
                var l_oCellSpacing = new PdfPCell(new Phrase(string.Empty));
                l_oCellSpacing.Border = Rectangle.NO_BORDER;
                l_oCellSpacing.Padding = 10;
                l_oCellSpacing.Colspan = 2;

                var l_oTableBlanc = new PdfPTable(2);
                l_oTableBlanc.AddCell(string.Empty);

                var l_oTablePrincipale = new PdfPTable(2);
                var l_oItextSharpFolderNodelist = l_oXmlDocument.SelectNodes("export/folder");

                XmlNodeList l_oItextSharpNodeImageList = null;
                XmlNodeList l_oNodeIndexList = null;
                var l_sImage = string.Empty;
                iTextSharp.text.Image l_oCurrentImage = null;
                PdfPCell l_oFolderNameCell = null;
                PdfPTable l_oTableIndex = null;
                PdfPCell l_oIndexCell = null;
                var l_sImageTemp = string.Empty;

                //Boucle sur les Folders
                foreach (XmlNode l_oNodeFolder in l_oItextSharpFolderNodelist)
                {
                    l_oFolderNameCell =
                        new PdfPCell(new Phrase(l_oNodeFolder.Attributes.GetNamedItem("name").Value,
                                                new Font(Font.FontFamily.COURIER,
                                                         m_oExporParameter.
                                                             ExportInventaireBiensFolderNameFontSize, 1,
                                                         BaseColor.BLACK)));

                    l_oItextSharpPageEventhandler.SetFolderName(l_oItextSharpWriter,
                                                                l_oNodeFolder.Attributes.GetNamedItem("name").Value);

                    l_oFolderNameCell.Padding = 0;
                    l_oFolderNameCell.Colspan = 2;
                    l_oFolderNameCell.Border = Rectangle.NO_BORDER;
                    l_oFolderNameCell.HorizontalAlignment = Element.ALIGN_LEFT;
                    l_oTablePrincipale.AddCell(l_oFolderNameCell);

                    l_oTablePrincipale.AddCell(l_oCellSpacing);

                    l_oItextSharpDocument.Add(l_oTablePrincipale);

                    l_oItextSharpNodeImageList = l_oNodeFolder.SelectNodes("images/image");

                    l_oTablePrincipale = new PdfPTable(2);
                    l_oCellSpacing.MinimumHeight = 5;


                    foreach (XmlNode l_oNodeimage in l_oItextSharpNodeImageList)
                    {
                        l_sImage = l_oNodeimage.Attributes.GetNamedItem("url").Value;

                        #region gestion de l'image

                        if (m_oExporParameter.ExportInventaireBiensImageQuality > 0)
                        {
                            if (IsFileTooLarge(new FileInfo(l_sImage),
                                               m_oExporParameter.ExportInventaireBiensImageQualityWeigthInKo))
                            {
                                l_sImageTemp = Path.Combine(l_sWorkingDirectory,
                                                            Guid.NewGuid().ToString("N") +
                                                            Constant.ImageFileFormat.JPEG.szGetDescription());
                                Image l_oImage = Image.FromFile(l_sImage);
                                // Encoder parameter for image quality 
                                var l_oQualityParam = new EncoderParameter(Encoder.Quality,
                                                                           (long)
                                                                           m_oExporParameter.
                                                                               ExportInventaireBiensImageQuality);
                                // Jpeg image codec 
                                var l_oJpegCodec = Treatments.GetEncoderInfo("image/jpeg");

                                var l_oEncoderParams = new EncoderParameters(1);
                                l_oEncoderParams.Param[0] = l_oQualityParam;

                                l_oImage.Save(l_sImageTemp, l_oJpegCodec, l_oEncoderParams);
                                l_oImage.Dispose();
                                l_sImage = l_sImageTemp;
                            }
                        }

                        l_oCurrentImage = iTextSharp.text.Image.GetInstance(l_sImage);

                        #endregion

                        l_oCurrentImage.ScaleToFit(250f, 250f);

                        var l_oCellImage = new PdfPCell(l_oCurrentImage);
                        l_oCellImage.Border = Rectangle.NO_BORDER;
                        l_oCellImage.Padding = 0;
                        l_oCellImage.HorizontalAlignment = Element.ALIGN_CENTER;
                        l_oCellImage.Colspan = 2;
                        l_oTablePrincipale.AddCell(l_oCellImage);

                        l_oTablePrincipale.AddCell(l_oCellSpacing);

                        l_oItextSharpDocument.Add(l_oTablePrincipale);

                        if (l_sImageTemp != string.Empty)
                        {
                            File.Delete(l_sImageTemp);
                            l_sImageTemp = string.Empty;
                        }
                        l_oTablePrincipale = new PdfPTable(2);
                    }

                    l_oNodeIndexList = l_oNodeFolder.SelectNodes("indexes/index");
                    l_oTableIndex = new PdfPTable(2);

                    foreach (XmlNode l_oNodeIndex in l_oNodeIndexList)
                    {
                        l_oIndexCell =
                            new PdfPCell(new Phrase(l_oNodeIndex.Attributes.GetNamedItem("name").Value,
                                                    new Font(Font.FontFamily.COURIER,
                                                             m_oExporParameter.
                                                                 ExportInventaireBiensIndexValueFontSize,
                                                             1, BaseColor.BLACK)));


                        l_oIndexCell.HorizontalAlignment = 3;
                        l_oIndexCell.Padding = 3;

                        l_oTableIndex.AddCell(l_oIndexCell);
                        l_oIndexCell =
                            new PdfPCell(new Phrase(l_oNodeIndex.Attributes.GetNamedItem("value").Value,
                                                    new Font(Font.FontFamily.COURIER,
                                                             m_oExporParameter.
                                                                 ExportInventaireBiensIndexValueFontSize,
                                                             1, BaseColor.BLUE)));

                        l_oIndexCell.HorizontalAlignment = 3;
                        l_oIndexCell.Padding = 3;

                        l_oTableIndex.AddCell(l_oIndexCell);
                    }
                    l_oItextSharpDocument.Add(l_oTableIndex);
                    l_oItextSharpDocument.NewPage();
                    l_oTablePrincipale = new PdfPTable(2);
                }

                var l_iNbPageContenu = l_oItextSharpWriter.PageNumber - 1;

                #endregion

                #region Page de garde

                l_oItextSharpPageEventhandler.m_bWritePageNumber = false;

                l_oItextSharpPageEventhandler.m_sHeaderTitle =
                    m_oExporParameter.ExportInventaireBiensHeaderPageGardeText1 + " - " +
                    m_oExporParameter.ExportInventaireBiensHeaderPageGardeText2;
                var l_oTablePageDeGarde = new PdfPTable(2);

                l_oCellSpacing.MinimumHeight = l_oItextSharpDocument.PageSize.Height/3;
                l_oTablePageDeGarde.AddCell(l_oCellSpacing);

                var l_oNodeExport = l_oXmlDocument.SelectSingleNode("export");

                var l_oCellPageDeGarde =
                    new PdfPCell(new Phrase(m_oExporParameter.ExportInventaireBiensPageGardeTitle,
                                            new Font(Font.FontFamily.COURIER,
                                                     m_oExporParameter.
                                                         ExportInventaireBiensPageGardeTitleFontSize, 1,
                                                     BaseColor.GRAY)));
                l_oCellPageDeGarde.Colspan = 2;
                l_oCellPageDeGarde.Padding = 10;
                l_oCellPageDeGarde.HorizontalAlignment = Element.ALIGN_CENTER;
                l_oCellPageDeGarde.Border = Rectangle.BOTTOM_BORDER;
                l_oTablePageDeGarde.AddCell(l_oCellPageDeGarde);

                l_oCellPageDeGarde =
                    new PdfPCell(new Phrase(l_oNodeExport.Attributes.GetNamedItem("user").Value,
                                            new Font(Font.FontFamily.COURIER,
                                                     m_oExporParameter.
                                                         ExportInventaireBiensPageGardeBodyFontSize, 1,
                                                     BaseColor.BLACK)));
                l_oCellPageDeGarde.Colspan = 2;
                l_oCellPageDeGarde.Padding = 10;
                l_oCellPageDeGarde.HorizontalAlignment = Element.ALIGN_CENTER;
                l_oCellPageDeGarde.Border = Rectangle.NO_BORDER;
                l_oTablePageDeGarde.AddCell(l_oCellPageDeGarde);

                l_oCellPageDeGarde =
                    new PdfPCell(new Phrase("[ " + l_oNodeExport.Attributes.GetNamedItem("date").Value + " ]",
                                            new Font(Font.FontFamily.COURIER,
                                                     m_oExporParameter.
                                                         ExportInventaireBiensPageGardeBodyFontSize, 1,
                                                     BaseColor.BLACK)));
                l_oCellPageDeGarde.Colspan = 2;
                l_oCellPageDeGarde.Padding = 10;
                l_oCellPageDeGarde.HorizontalAlignment = Element.ALIGN_CENTER;
                l_oCellPageDeGarde.Border = Rectangle.NO_BORDER;
                l_oTablePageDeGarde.AddCell(l_oCellPageDeGarde);

                l_oItextSharpDocument.Add(l_oTablePageDeGarde);
                l_oItextSharpDocument.NewPage();
                l_oItextSharpDocument.Add(l_oTableBlanc);

                #endregion

                #region Summary

                l_oItextSharpPageEventhandler.m_sHeaderTitle = m_oExporParameter.ExportInventaireBiensHeaderPageText;

                l_oItextSharpDocument.Add(l_oTableBlanc);

                var l_oTableSommaire = new PdfPTable(2);


                var l_oSummaryTitleCell =
                    new PdfPCell(new Phrase(m_oExporParameter.ExportInventaireBiensSummaryTitle,
                                            new Font(Font.FontFamily.COURIER,
                                                     m_oExporParameter.
                                                         ExportInventaireBiensFolderNameFontSize, 1,
                                                     BaseColor.BLACK)));

                l_oSummaryTitleCell.Padding = 0;
                l_oSummaryTitleCell.Colspan = 2;
                l_oSummaryTitleCell.Border = Rectangle.NO_BORDER;
                l_oSummaryTitleCell.HorizontalAlignment = Element.ALIGN_LEFT;


                l_oTableSommaire.AddCell(l_oSummaryTitleCell);

                l_oCellSpacing.MinimumHeight = 20;
                l_oTableSommaire.AddCell(l_oCellSpacing);

                foreach (var VARIABLE in l_oItextSharpPageEventhandler.l_oDicSummary.Keys)
                {
                    l_oCellFolder = new PdfPCell(new Phrase(l_oItextSharpPageEventhandler.l_oDicSummary[VARIABLE],
                                                            new Font(
                                                                Font.FontFamily.COURIER,
                                                                m_oExporParameter.
                                                                    ExportInventaireBiensIndexNameFontSize, 1,
                                                                BaseColor.BLACK)));
                    l_oCellFolder.Border = Rectangle.NO_BORDER;
                    l_oCellFolder.Padding = 3;
                    l_oCellFolder.HorizontalAlignment = Element.ALIGN_LEFT;
                    l_oTableSommaire.AddCell(l_oCellFolder);

                    l_oCellFolder = new PdfPCell(new Phrase(VARIABLE.ToString(),
                                                            new Font(
                                                                Font.FontFamily.COURIER,
                                                                m_oExporParameter.
                                                                    ExportInventaireBiensIndexNameFontSize, 1,
                                                                BaseColor.BLACK)));
                    l_oCellFolder.Border = Rectangle.NO_BORDER;
                    l_oCellFolder.HorizontalAlignment = Element.ALIGN_RIGHT;
                    l_oCellFolder.Padding = 3;
                    l_oTableSommaire.AddCell(l_oCellFolder);
                }

                l_oItextSharpDocument.Add(l_oTableSommaire);

                l_oItextSharpDocument.NewPage();

                var l_iNbPageSommaire = l_oItextSharpWriter.PageNumber;

                #endregion

                #region Réorganisation page

                var l_oPageReordered = new int[l_oItextSharpWriter.PageNumber - 1];

                var l_iCurrent_i = 0;
                for (var i = l_iNbPageContenu + 1; i < l_iNbPageSommaire; i++)
                {
                    l_oPageReordered[l_iCurrent_i] = i;
                    l_iCurrent_i++;
                }

                for (var i = 1; i <= l_iNbPageContenu; i++)
                {
                    l_oPageReordered[l_iCurrent_i] = i;
                    l_iCurrent_i++;
                }

                l_oItextSharpWriter.ReorderPages(l_oPageReordered);

                #endregion

                l_oItextSharpDocument.Close();
                l_oItextSharpWriter.Close();
                l_oXmlDocument = null;
                File.Delete(l_sXmlDataFileFullPath);
                Directory.Delete(l_sWorkingDirectory, true);

                try
                {
                    MailAddress l_oMailAddress = new MailAddress(p_sUserEmailAdress);
                    Smtp.SendMail(ConfigurationManager.AppSettings.Get("SmtpServer"),
                                  m_oExporParameter.ExportInventaireBiensMailSubject + "-----" +
                                  DateTime.Now.ToString("dd/mm/yyyy"), m_oExporParameter.ExportInventaireBiensMailBody,
                                  new MailAddress(string.Empty, "Rio 5"), new List<MailAddress> {l_oMailAddress}, null,
                                  null);
                }
                catch (Exception SendMailException)
                {
                    LogManager.Instance().LogError(
                        "------------- EXCEPTION IN WCF GenerateReport send mail EXCEPTION[" + DateTime.Now +
                        "] Message [" + SendMailException.Message + "]");
                }
            }
            catch (Exception ex)
            {
                LogManager.Instance().LogError(
                    "------------- EXCEPTION IN WCF GenerateReport EXCEPTION[" + DateTime.Now + "] Message [" +
                    ex.Message + "]");
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---GenerateReport-----------------");
            LogManager.Instance().LogInfo("END OF WCF SERVICE CALL ---------------------");
        }

        /// <summary>
        ///   Create a file in order to tell the application to refresh the thumbnail list
        /// </summary>
        /// <param name="p_sGuidToString"> A guid ToString("N") </param>
        public ReturnBoolean CreateRefreshFile(string p_sGuidToString)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---CreateRefreshFile----- p_sGuidToString[" + p_sGuidToString +
                                          "]");

            var l_oReturnBoolean = new ReturnBoolean {Value = true};
            var l_sTemporaryDirectoryDirectory =
                ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory");

            try
            {
                Treatments.CheckDirectory(l_sTemporaryDirectoryDirectory);
                var l_sFullPathOfRefreshFile = Path.Combine(l_sTemporaryDirectoryDirectory,
                                                            p_sGuidToString
                    );
                LogManager.Instance().LogInfo("-------CreateRefreshFile----- Creating file[" +
                                              l_sFullPathOfRefreshFile + "]");
                if (!File.Exists(l_sFullPathOfRefreshFile))
                {
                    using (var fs = File.Create(l_sFullPathOfRefreshFile))
                    {
                        fs.WriteByte(0);
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Instance().LogError(ex.Message);
                l_oReturnBoolean.Value = false;
                Treatments.DeleteDirectory(l_sTemporaryDirectoryDirectory);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---CreateRefreshFile-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return l_oReturnBoolean;
        }

        /// <summary>
        ///   Create a temporary directory
        /// </summary>
        /// <param name="p_sGuid"> Name of the director </param>
        /// <param name="p_oMessageRequest"> </param>
        /// <returns> A ReturnBoolean object with all relevant information </returns>
        public ReturnBoolean CreateTemporaryDirectory(string p_sGuid, MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---CreateDirectory-----p_sGuid[" + p_sGuid +
                                          "]--------------");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            var l_oReturnBoolean = new ReturnBoolean
                                       {
                                           Value =
                                               Treatments.CheckDirectory(
                                                   Path.Combine(
                                                       ConfigurationManager.AppSettings.Get(
                                                           "Rio.WCF.Services.TemporaryDirectory"), p_sGuid))
                                       };

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---CreateDirectory-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return l_oReturnBoolean;
        }

        /// <summary>
        ///   Add a file to the merge process
        /// </summary>
        /// <param name="p_sGuid"> Name of the temporary directory </param>
        /// <param name="p_sFileName"> the file name to convert into a pdf file </param>
        /// <param name="p_lUserId"> the user id </param>
        /// <param name="p_oMessageRequest"> </param>
        /// <param name="p_bImport"> Are we in import or not </param>
        /// <returns> A ReturnBoolean object with all relevant information </returns>
        public ReturnBoolean ConvertDocumentAppend(string p_sGuid, string p_sFileName, long p_lUserId,
                                                   MessageRequest p_oMessageRequest, bool p_bImport = false)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---ConvertDocumentAppend-----p_sGuid[" + p_sGuid +
                                          "] p_sFileName[" + p_sFileName + "] p_lUserId[" + p_lUserId +
                                          "]--------------");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            var l_sDocumentFullPath = p_bImport ? GetImportDocumentFullPath(p_sFileName, p_lUserId) : p_sFileName;

            var l_sGuidDirectory =
                Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory"), p_sGuid);
            var l_oDi = new DirectoryInfo(l_sGuidDirectory);

            ReturnString l_oReturnString = new ReturnString();
            if (l_oDi.Exists)
            {
                l_oDi.GetFiles("*" + Constant.DocumentFileFormat.PDF.szGetDescription());

                // For the first part of a file we create a file with the name fo the file with a "txt" extension
                // This will help us to rename the file with the original filename after the last part of the file will be sent.
                // We have to do this because the slice are renamed in a way to oder file.
                if (l_oDi.GetFiles("*.*").Count() == 0)
                {
                    using (
                        var fs =
                            File.Create(Path.Combine(l_sGuidDirectory,
                                                     Path.GetFileNameWithoutExtension(l_sDocumentFullPath) +
                                                     Constant.DocumentFileFormat.TXT.szGetDescription())))
                    {
                        fs.WriteByte(0);
                    }
                }

                var l_sFinalFileName =
                    l_oDi.GetFiles("*" + Constant.DocumentFileFormat.PDF.szGetDescription()).Count().ToString(
                        "000000000000000") + Guid.NewGuid().ToString("N") +
                    Constant.DocumentFileFormat.PDF.szGetDescription();

                l_oReturnString = MergeDocumentFullPathInPdf(l_sDocumentFullPath,
                                                             Path.Combine(l_sGuidDirectory, l_sFinalFileName),
                                                             p_oMessageRequest);

                LogManager.Instance().LogInfo(string.Empty);
                LogManager.Instance().LogInfo("---ConvertDocumentAppend-----------------");
                LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");
            }
            return new ReturnBoolean {IsValid = l_oReturnString.IsValid};
        }

        /// <summary>
        ///   the end of the merge process
        /// </summary>
        /// <param name="p_sGuid"> the temporary directory where all files are stored </param>
        /// <param name="p_lUserId"> the user identifier </param>
        /// <param name="p_oMessageRequest"> </param>
        /// <param name="p_bUsePrintMode"> Is it an import merge or print file merge </param>
        /// <returns> A ReturnString object with all relevant information </returns>
        public ReturnString ConvertDocumentFinish(string p_sGuid, long p_lUserId, MessageRequest p_oMessageRequest,
                                                  bool p_bUsePrintMode = false)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---ConvertDocumentFinish-----p_sGuid[" + p_sGuid +
                                          "] p_bUsePrintMode[" + p_bUsePrintMode + "]--------------");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            var l_oReturnString = new ReturnString();

            try
            {
                var l_sGuidDirectory =
                    Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory"), p_sGuid);
                var l_oDi = new DirectoryInfo(l_sGuidDirectory);

                var l_oRgFiles = l_oDi.GetFiles("*" + Constant.DocumentFileFormat.PDF.szGetDescription());
                var l_oOrderedFiles = l_oRgFiles.OrderBy(f => f.Name);

                string l_sFinalFileName;
                if (l_oRgFiles.Count() > 1)
                {
                    l_sFinalFileName = !p_bUsePrintMode
                                           ? GetImportDocumentFullPath(
                                               DateTime.Now.ToString("yyyyMMddhhmmssfff") +
                                               Constant.DocumentFileFormat.PDF.szGetDescription(), p_lUserId)
                                           : Path.Combine(l_sGuidDirectory,
                                                          DateTime.Now.ToString("yyyyMMddhhmmssfff") +
                                                          Constant.DocumentFileFormat.PDF.szGetDescription());

                    LogManager.Instance().LogInfo(
                        "------------------------ Merging all pdf (l_oDi.GetFiles(*.pdf).Count() [" +
                        l_oDi.GetFiles("*" + Constant.DocumentFileFormat.PDF.szGetDescription()).Count() + "] to [" +
                        l_sFinalFileName + "]---------");

                    var l_lstFileNameFullPath = l_oOrderedFiles.Select(l_oFileInfo => l_oFileInfo.FullName).ToList();

                    MergePdfFiles(l_sFinalFileName, l_lstFileNameFullPath);
                }
                else
                {
                    var l_oDiTxt = new DirectoryInfo(l_sGuidDirectory);
                    var l_oOrderedFilesTxt = l_oDiTxt.GetFiles("*" + Constant.DocumentFileFormat.TXT.szGetDescription());

                    l_sFinalFileName =
                        GetImportDocumentFullPath(
                            Path.GetFileNameWithoutExtension(l_oOrderedFilesTxt.First().Name) +
                            Constant.DocumentFileFormat.PDF.szGetDescription(), p_lUserId);
                    LogManager.Instance().LogInfo("------------------------ Copying file from  [" +
                                                  l_oOrderedFiles.First().FullName + "] to [" +
                                                  l_sFinalFileName + "]---------");
                    if (!p_bUsePrintMode)
                    {
                        File.Copy(l_oOrderedFiles.First().FullName, l_sFinalFileName, true);
                    }
                    else
                    {
                        l_sFinalFileName = l_oOrderedFiles.First().FullName;
                    }
                }


                if (!p_bUsePrintMode)
                {
                    using (Treatments l_oTreatments = new Treatments())
                    {
                        l_oTreatments.CreateThumb(l_sFinalFileName,
                                                  GetThumbDocumentFullPath(Path.GetFileName(l_sFinalFileName), p_lUserId));
                    }
                }
                l_oReturnString.Value = l_sFinalFileName;
            }
            catch (Exception ex)
            {
                LogManager.Instance().LogError(
                    "------------- EXCEPTION IN WCF DeleteDirectory EXCEPTION[" + DateTime.Now + "] Message [" +
                    ex.Message + "]");
                l_oReturnString.IsValid = false;
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---ConvertDocumentFinish-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return l_oReturnString;
        }

        /// <summary>
        ///   Delete a file in order to stop the refresh
        /// </summary>
        /// <param name="p_sGuidToString"> A guid ToString("N") </param>
        public void DeleteRefreshFile(string p_sGuidToString)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---DeleteRefreshFile----- p_sGuidToString[" + p_sGuidToString +
                                          "]");

            try
            {
                var l_sFullPathOfRefreshFile =
                    Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory"),
                                 p_sGuidToString);
                LogManager.Instance().LogInfo("-------DeleteRefreshFile----- Deleting file[" +
                                              l_sFullPathOfRefreshFile + "]");
                if (File.Exists(l_sFullPathOfRefreshFile))
                    File.Delete(l_sFullPathOfRefreshFile);
            }
            catch (Exception ex)
            {
                LogManager.Instance().LogError(ex.Message);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---DeleteRefreshFile-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");
        }

        /// <summary>
        ///   Delete a temporary directory
        /// </summary>
        /// <param name="p_sGuid"> The name of the teporary dorectory </param>
        /// <param name="p_oMessageRequest"> </param>
        /// <returns> A ReturnBoolean object with all relevant information </returns>
        public ReturnBoolean DeleteTemporaryDirectory(string p_sGuid, MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---DeleteDirectory-----p_sDirectoryPath[" +
                                          Path.Combine(
                                              ConfigurationManager.AppSettings.Get(
                                                  "Rio.WCF.Services.TemporaryDirectory"), p_sGuid) + "]");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            var l_oReturnBoolean = new ReturnBoolean();
            try
            {
                DeleteDirectory(
                    Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory"), p_sGuid),
                    p_oMessageRequest);
            }
            catch (Exception ex)
            {
                LogManager.Instance().LogError(
                    "------------- EXCEPTION IN WCF DeleteDirectory EXCEPTION[" + DateTime.Now + "] Message [" +
                    ex.Message + "]");
                l_oReturnBoolean.IsValid = false;
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---DeleteDirectory-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return l_oReturnBoolean;
        }

        /// <summary>
        ///   Cleans the cache directory.
        /// </summary>
        /// <param name="p_oMessageRequest"> The p_o message request. </param>
        /// <returns> </returns>
        public void CleanCacheDirectory(MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");

            CacheManager.CleanCacheDirectory();

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---CleanCacheDirectory-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");
        }

        /// <summary>
        ///   Delete a list of import directories (document(s) and its thumbnail(s))
        /// </summary>
        /// <param name="p_sDirectoriesList"> The P_S directories list. </param>
        /// <param name="p_iUserId"> User identifier </param>
        /// <param name="p_oMessageRequest"> The p_o message request. </param>
        /// <returns> the returnboolean object with the correspondant value </returns>
        public ReturnBoolean DeleteImportDirectories(List<string> p_sDirectoriesList, long p_iUserId,
                                                     MessageRequest p_oMessageRequest)
        {
            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            var l_oReturnBooleanImport = new ReturnBoolean();
            l_oReturnBooleanImport.IsValid = true;

            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---DeleteImportDirectories------p_DirectoryName(" +
                                          p_sDirectoriesList + ")--p_iUserId(" + p_iUserId +
                                          ")--------------------" + DateTime.Now);

            //each directories to delete
            foreach (var Dir in p_sDirectoriesList)
            {
                //delete thumbnail files and dir
                var l_sOutputDirectoryFullPath =
                    Path.Combine(
                        Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.OutputDirectory"),
                                     p_iUserId.ToString()), Dir);
                if (Directory.Exists(l_sOutputDirectoryFullPath))
                {
                    var l_oDi = new DirectoryInfo(l_sOutputDirectoryFullPath);
                    FileInfo[] l_oRgFiles = l_oDi.GetFiles("*" + Constant.ImageFileFormat.JPG.szGetDescription());
                    l_oReturnBooleanImport = DeleteDocumentWithFullPath(l_oRgFiles.ConvertToList(), p_oMessageRequest);
                    DeleteDirectory(l_sOutputDirectoryFullPath, p_oMessageRequest);
                }

                //Delete images files and dir
                var l_sInputDirectoryFullPath =
                    Path.Combine(
                        Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.InputDirectory"),
                                     p_iUserId.ToString()), Dir);
                if (Directory.Exists(l_sInputDirectoryFullPath))
                {
                    var l_oDi = new DirectoryInfo(l_sInputDirectoryFullPath);
                    FileInfo[] l_oRgFiles = l_oDi.GetFiles("*" + Constant.ImageFileFormat.JPG.szGetDescription());
                    l_oReturnBooleanImport = DeleteDocumentWithFullPath(l_oRgFiles.ConvertToList(), p_oMessageRequest);
                    DeleteDirectory(l_sInputDirectoryFullPath, p_oMessageRequest);
                }
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---DeleteImportDirectories---------------------------");
            LogManager.Instance().LogInfo("END OF WCF SERVICE CALL ---------------------");
            LogManager.Instance().LogInfo(
                "----------------------------------------------------------------------");
            return l_oReturnBooleanImport;
        }

        /// <summary>
        ///   Delete a document and its thumbnail
        /// </summary>
        /// <param name="p_lstDocumentName"> List of all document name to delete </param>
        /// <param name="p_iUserId"> User identifier </param>
        /// <param name="p_oMessageRequest"> </param>
        /// <returns> the returnboolean object with the correspondant value </returns>
        public ReturnBoolean DeleteImportDocument(List<string> p_lstDocumentName, long p_iUserId,
                                                  MessageRequest p_oMessageRequest)
        {
            Treatments.CheckApplicationRequestKey(p_oMessageRequest);
            var l_oReturnBooleanImport = new ReturnBoolean();

            l_oReturnBooleanImport.IsValid = true;

            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---DeleteImportDocument------p_lstDocumentName(" +
                                          p_lstDocumentName + ")--p_iUserId(" + p_iUserId +
                                          ")--------------------" + DateTime.Now);

            var l_lstFileName = new List<string>();
            foreach (var l_oFileName in p_lstDocumentName)
            {
                #region Deleting ThumbNailImage

                var l_sImageFullPath = GetThumbDocumentFullPath(l_oFileName, p_iUserId);
                LogManager.Instance().LogInfo("------------ DELETING THUMB FILE [" + l_sImageFullPath +
                                              "]");
                l_lstFileName.Add(l_sImageFullPath);
                Treatments.DeleteFile(l_sImageFullPath);
                l_lstFileName.Clear();

                #endregion

                #region Deleting Original Image

                l_sImageFullPath = GetImportDocumentFullPath(l_oFileName, p_iUserId);
                LogManager.Instance().LogInfo("------------ DELETING ORIGINAL FILE [" + l_sImageFullPath +
                                              "]");
                l_lstFileName.Add(l_sImageFullPath);
                Treatments.DeleteFile(l_sImageFullPath);
                l_lstFileName.Clear();

                #endregion

                Treatments.DeleteAllImportCacheFiles(p_iUserId, l_oFileName);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---DeleteImportDocument---------------------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");
            LogManager.Instance().LogInfo(
                "----------------------------------------------------------------------");
            return l_oReturnBooleanImport;
        }

        /// <summary>
        ///   Delete a document and its thumbnail
        /// </summary>
        /// <param name="p_lstDocumentName"> List of all document name to delete </param>
        /// <param name="p_iUserId"> User identifier </param>
        /// <param name="p_oMessageRequest"> </param>
        /// <returns> the returnboolean object with the correspondant value </returns>
        public ReturnBoolean DeleteImportImages(List<ImageRio> p_lstDocumentName, long p_iUserId,
                                                MessageRequest p_oMessageRequest)
        {
            Treatments.CheckApplicationRequestKey(p_oMessageRequest);
            var l_oReturnBooleanImport = new ReturnBoolean();
            l_oReturnBooleanImport.IsValid = true;

            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---DeleteImportImages------p_lstDocumentName(" +
                                          p_lstDocumentName.ToList() + ")--p_iUserId(" + p_iUserId +
                                          ")--------------------" + DateTime.Now);

            //delete documents and directories
            List<string> l_oListDirectories =
                p_lstDocumentName.FindAll(d => d.isDirectory).ConvertAll(n => Utils.RemoveExtension(n.Name)).ToList();
            l_oReturnBooleanImport = DeleteImportDirectories(l_oListDirectories, p_iUserId, p_oMessageRequest);
            if (l_oReturnBooleanImport.IsValid)
            {
                List<string> l_oListFiles =
                    p_lstDocumentName.FindAll(d => !d.isDirectory).ConvertAll(n => Utils.RemoveExtension(n.Name)).ToList
                        ();
                l_oReturnBooleanImport = DeleteImportDocument(l_oListFiles, p_iUserId, p_oMessageRequest);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---DeleteImportImages---------------------------");
            LogManager.Instance().LogInfo("END OF WCF SERVICE CALL ---------------------");
            LogManager.Instance().LogInfo(
                "----------------------------------------------------------------------");
            return l_oReturnBooleanImport;
        }

        /// <summary>
        ///   Get the thumbnail list of a user
        /// </summary>
        /// <param name="p_iUserId"> User Identifier </param>
        /// <param name="p_bOrderByDescending"> if set to <c>true</c> [P_B order by descending]. </param>
        /// <param name="p_oMessageRequest"> The p_o message request. </param>
        /// <returns> The list of all imageRio available </returns>
        public List<ImageRio> GetImportThumbNailList(long p_iUserId, bool p_bOrderByDescending,
                                                     MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---GetImportThumbNailList-----p_iUserId[" + p_iUserId +
                                          "]--------------");

            return GetImportThumbNailListFromPath(p_iUserId, null, p_bOrderByDescending, p_oMessageRequest);
        }

        /// <summary>
        ///   Get the thumbnail list of a user in the specified directory
        /// </summary>
        /// <param name="p_iUserId"> User Identifier </param>
        /// <param name="p_directoryPath"> Directory </param>
        /// <param name="p_bOrderByDescending"> if set to <c>true</c> [P_B order by descending]. </param>
        /// <param name="p_oMessageRequest"> The p_o message request. </param>
        /// <returns> The list of all imageRio available </returns>
        public List<ImageRio> GetImportThumbNailListFromPath(long p_iUserId, string p_directoryPath,
                                                             bool p_bOrderByDescending, MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---GetImportThumbNailListFromPath-----p_iUserId[" + p_iUserId +
                                          "]--------------");
            LogManager.Instance().LogInfo("---GetImportThumbNailListFromPath-----p_directoryPath[" +
                                          p_directoryPath + "]--------------");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            var l_oLstImageRio = new List<ImageRio>();
            try
            {
                var l_sDirectory = Path.Combine(
                    ConfigurationManager.AppSettings.Get("Rio.WCF.Services.OutputDirectory"), p_iUserId.ToString());
                if (!string.IsNullOrEmpty(p_directoryPath))
                {
                    //Combine with the subdir
                    if (Path.IsPathRooted(p_directoryPath))
                    {
                        l_sDirectory = Path.Combine(l_sDirectory, Path.GetDirectoryName(p_directoryPath));
                    }
                    else
                    {
                        l_sDirectory = Path.Combine(l_sDirectory, p_directoryPath);
                    }
                }

                if (Directory.Exists(l_sDirectory))
                {
                    //Step1 Get all thumbnails Files in the specified Path 
                    var l_oDi = new DirectoryInfo(l_sDirectory);
                    var l_oRgFiles = l_oDi.GetFiles("*" + Constant.ImageFileFormat.JPG.szGetDescription());
                    //var l_oOrderedFiles = l_oRgFiles.OrderByDescending(f => f.CreationTime);

                    IOrderedEnumerable<FileInfo> l_oOrderedFiles = null;
                    l_oOrderedFiles = (p_bOrderByDescending
                                           ? l_oRgFiles.OrderByDescending(f => f.CreationTime)
                                           : l_oRgFiles.OrderBy(f => f.CreationTime));

                    var l_lstImageFullPath = l_oOrderedFiles.Select(l_oFi => l_oFi.FullName).ToList();
                    LogManager.Instance().LogInfo("------------- Calling GetImageFromFullPath[" +
                                                  DateTime.Now + "]");
                    l_oLstImageRio = GetImageFromFullPathByUserId(l_lstImageFullPath, null, p_iUserId, p_directoryPath,
                                                                  p_oMessageRequest);

                    //Step2 Get All directories thumbnails
                    var l_oRgDirs = l_oDi.GetDirectories();
                    foreach (DirectoryInfo l_sDirectoryFullPath in l_oRgDirs)
                    {
                        if (ImageRio.isValidDirectoryName(l_sDirectoryFullPath.Name))
                        {
                            ImageRio l_oImageRio = new ImageRio();
                            l_oImageRio.ImageType =
                                ImageRio.ConvertDirectoryNameToImageRioType(l_sDirectoryFullPath.Name);
                            l_oImageRio.Name = l_sDirectoryFullPath.Name;
                            l_oImageRio.FullPath = l_sDirectoryFullPath.FullName;

                            FileInfo[] files =
                                l_sDirectoryFullPath.GetFiles("*" + Constant.ImageFileFormat.JPG.szGetDescription());
                            if (files.Length > 0)
                                l_oImageRio.NumberPages = files.Length;
                            else
                                continue;

                            // Add all files inside the directory
                            l_oImageRio.FileList = GetImageFromFullPathByUserId(files.ConvertToListWithFullName(), null,
                                                                                p_iUserId, l_sDirectoryFullPath.Name,
                                                                                p_oMessageRequest);

                            //select Icons
                            l_oImageRio.Img =
                                GetIconData(l_oImageRio.ImageType.ToString() +
                                            Constant.ImageFileFormat.PNG.szGetDescription());
                            l_oLstImageRio.Add(l_oImageRio);
                        }
                    }
                }
                else
                {
                    LogManager.Instance().LogInfo("-------------  Directory [" + l_sDirectory +
                                                  "] does not exists");
                }
            }
            catch (Exception ex)
            {
                var l_oImageRio =
                    new ImageRio(
                        "------------- EXCEPTION IN WCF GetImportThumbNailListFromPath EXCEPTION[" + DateTime.Now + "]",
                        new Exception(ex.Message));
                LogManager.Instance().LogError(l_oImageRio.FullErrorMessage);
                l_oLstImageRio.Add(l_oImageRio);
            }
            LogManager.Instance().LogInfo("---------------------------------[" + l_oLstImageRio.Count +
                                          "] thumb found--------------");
            LogManager.Instance().LogInfo("---GetImportThumbNailListFromPath-----------------");
            LogManager.Instance().LogInfo("END OF WCF SERVICE CALL ---------------------");

            return l_oLstImageRio;
        }

        /// <summary>
        ///   Get images from list of full path
        /// </summary>
        /// <param name="p_lstImageFullPath"> List of all images full path </param>
        /// <param name="p_lstOriginalImageFullPath"> The P_LST original image full path. </param>
        /// <param name="p_oMessageRequest"> The p_o message request. </param>
        /// <returns> The list of all imageRio corresponding </returns>
        public List<ImageRio> GetImageFromFullPath(List<string> p_lstImageFullPath,
                                                   List<string> p_lstOriginalImageFullPath,
                                                   MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---GetImageFromFullPath-----p_lstImageFullPath.Count[" +
                                          p_lstImageFullPath.Count + "]--------------");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            var l_oLstImageRio = new List<ImageRio>();
            ImageRio l_oImageRio;
            try
            {
                var l_iCpt = 0;
                foreach (var l_sFileNameFullPath in p_lstImageFullPath)
                {
                    if (File.Exists(l_sFileNameFullPath))
                    {
                        var l_oFi = new FileInfo(l_sFileNameFullPath);
                        var l_bFileTransfered = false;
                        FileStream l_oFileStream = null;
                        // We must loop until the file is completely transfered by the webservice because the FileSystemWatcher fires the event as soon
                        // as a new file ( even not complete ) is created in the directory.
                        while (!l_bFileTransfered)
                        {
                            try
                            {
                                using (File.OpenRead(l_oFi.FullName))
                                {
                                    l_oFileStream = new FileStream(l_oFi.FullName, FileMode.Open, FileAccess.Read,
                                                                   FileShare.ReadWrite);
                                    l_bFileTransfered = true;
                                }
                            }
                                // Catch to wait until file is completely transfered in the directory
                            catch
                            {
                            }
                        }

                        // get file length
                        var l_iLength = (int) l_oFileStream.Length;
                        // create buffer
                        var l_oBuffer = new byte[l_iLength];
                        // actual number of bytes read
                        int l_iCount;
                        // total number of bytes read
                        var sum = 0;

                        // read until Read method returns 0 (end of the stream has been reached)
                        while ((l_iCount = l_oFileStream.Read(l_oBuffer, sum, l_iLength - sum)) > 0)
                            sum += l_iCount; // sum is a buffer offset for next reading

                        l_oFileStream.Dispose();
                        l_oFileStream.Close();

                        l_oImageRio = new ImageRio(l_oFi.Name, l_oBuffer, l_oFi.Length);


                        FileInfo l_oFileInfoOriginalFile;
                        if (p_lstOriginalImageFullPath == null)
                        {
                            l_oFileInfoOriginalFile =
                                new FileInfo(GetImportDocumentFullPath(Path.GetFileNameWithoutExtension(l_oFi.FullName),
                                                                       long.Parse(l_oFi.Directory.Name)));
                        }
                        else
                        {
                            l_oFileInfoOriginalFile =
                                new FileInfo(p_lstOriginalImageFullPath[l_iCpt]);
                        }

                        l_oImageRio.NumberPages = GetNumberOfPageInDocument(l_oFileInfoOriginalFile);

                        if (l_oFileInfoOriginalFile.Exists)
                            Treatments.FillMetadata(l_oFileInfoOriginalFile, ref l_oImageRio, EnableMetaData);

                        l_oLstImageRio.Add(l_oImageRio);

                        l_oBuffer = null;
                    }
                    else
                    {
                        l_oImageRio =
                            new ImageRio("------- EXCEPTION IN WCF GetImageFromFullPath. The file [" +
                                         l_sFileNameFullPath + "] does not exists-----------------");
                        LogManager.Instance().LogError(l_oImageRio.FullErrorMessage);
                    }
                    l_iCpt++;
                }
            }
            catch (Exception ex)
            {
                l_oImageRio =
                    new ImageRio("------------- EXCEPTION IN WCF GetImageFromFullPath EXCEPTION[" + DateTime.Now + "]",
                                 new Exception(ex.Message));
                LogManager.Instance().LogError(l_oImageRio.FullErrorMessage);
                l_oLstImageRio.Add(l_oImageRio);
            }

            LogManager.Instance().LogInfo("---------------------------------[" + l_oLstImageRio.Count +
                                          "] thumb found--------------" + DateTime.Now);
            LogManager.Instance().LogInfo("---GetImageFromFullPath-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return l_oLstImageRio;
        }

        /// <summary>
        ///   Return the number of pages of a Tiff file
        /// </summary>
        /// <param name="p_sTiffFileName"> Document Name </param>
        /// <param name="p_iUserId"> The user identifier </param>
        /// <param name="p_oMessageRequest"> The p_o message request. </param>
        /// <returns> the number of page of the document </returns>
        public ReturnLong GetImportCountTiffPages(string p_sTiffFileName, long p_iUserId,
                                                  MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---GetImportCountTiffPages-----p_sTiffFileName[" +
                                          p_sTiffFileName + "]---p_iUserId[" + p_iUserId + "]");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            ReturnLong l_oReturnLong;
            try
            {
                l_oReturnLong = GetPageCountFromTiffFullPath(GetImportDocumentFullPath(p_sTiffFileName, p_iUserId),
                                                             p_oMessageRequest);
            }
            catch (Exception ex)
            {
                l_oReturnLong =
                    new ReturnLong(
                        "------------- EXCEPTION IN WCF GetImportCountTiffPages EXCEPTION[" + DateTime.Now + "]",
                        new Exception(ex.Message));
                LogManager.Instance().LogError(l_oReturnLong.FullErrorMessage);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---GetImportCountTiffPages-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return l_oReturnLong;
        }

        /// <summary>
        ///   Return the number of pages of a Pdf file
        /// </summary>
        /// <param name="p_sPdfFileName"> Document Name </param>
        /// <param name="p_iUserId"> The user identifier </param>
        /// <param name="p_oMessageRequest"> The p_o message request. </param>
        /// <returns> the number of page of the document </returns>
        public ReturnLong GetImportCountPdfPages(string p_sPdfFileName, long p_iUserId, MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---GetImportCountPdfPages-----p_sTiffFileName[" +
                                          p_sPdfFileName + "]---p_iUserId[" + p_iUserId + "]");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            ReturnLong l_oReturnLong;
            try
            {
                l_oReturnLong = GetPageCountFromPdfFullPath(GetImportDocumentFullPath(p_sPdfFileName, p_iUserId),
                                                            p_oMessageRequest);
            }
            catch (Exception ex)
            {
                l_oReturnLong =
                    new ReturnLong(
                        "------------- EXCEPTION IN WCF GetImportCountPdfPages EXCEPTION[" + DateTime.Now + "]",
                        new Exception(ex.Message));
                LogManager.Instance().LogError(l_oReturnLong.FullErrorMessage);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---GetImportCountPdfPages-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return l_oReturnLong;
        }

        /// <summary>
        ///   Return the number of page of a Pdf file
        /// </summary>
        /// <param name="p_sPdfFileFullPath"> Document full path </param>
        /// <param name="p_oMessageRequest"> </param>
        /// <returns> the number of page of the document </returns>
        public ReturnLong GetPageCountFromPdfFullPath(string p_sPdfFileFullPath, MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---GetPageCountFromPdfFullPath-----p_sTiffFileFullPath[" +
                                          p_sPdfFileFullPath + "]");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            var l_oReturnLong = new ReturnLong();
            try
            {
                if (!File.Exists(p_sPdfFileFullPath))
                {
                    throw new FileNotFoundException(
                        "------------- EXCEPTION IN WCF GetPageCountFromPdfFullPath EXCEPTION: [ This file [" +
                        p_sPdfFileFullPath + "] does not exists]");
                }
                if (new FileInfo(p_sPdfFileFullPath).Extension.ToLower() !=
                    Constant.DocumentFileFormat.PDF.szGetDescription()
                    &&
                    new FileInfo(p_sPdfFileFullPath).Extension.ToLower() !=
                    Constant.DocumentFileFormat.PDF.szGetDescription())
                {
                    throw new Exception(
                        "------------- EXCEPTION IN WCF GetPageCountFromPdfFullPath EXCEPTION: [ The Extension of the file is not supported [" +
                        p_sPdfFileFullPath + "]. Only Tif file are supported.]");
                }

                var l_oReader = new PdfReader(p_sPdfFileFullPath);
                l_oReturnLong.Value = l_oReader.NumberOfPages;
                l_oReader.Close();
            }
            catch (Exception ex)
            {
                l_oReturnLong =
                    new ReturnLong(
                        "------------- EXCEPTION IN WCF GetPageCountFromPdfFullPath EXCEPTION[" + DateTime.Now + "]",
                        new Exception(ex.Message));
                LogManager.Instance().LogError(l_oReturnLong.FullErrorMessage);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---GetPageCountFromPdfFullPath-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return l_oReturnLong;
        }

        /// <summary>
        ///   Return the number of pages of a Tiff file
        /// </summary>
        /// <param name="p_sTiffFileFullPath"> Document full path </param>
        /// <returns> the number of page of the document </returns>
        public ReturnLong GetPageCountFromTiffFullPath(string p_sTiffFileFullPath, MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---GetPageCountFromTiffFullPath-----p_sTiffFileFullPath[" +
                                          p_sTiffFileFullPath + "]");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            var l_oReturnLong = new ReturnLong();
            try
            {
                if (!File.Exists(p_sTiffFileFullPath))
                {
                    throw new FileNotFoundException(
                        "------------- EXCEPTION IN WCF GetPageCountFromTiffFullPath EXCEPTION: [ This file [" +
                        p_sTiffFileFullPath + "] does not exists]");
                }
                if (new FileInfo(p_sTiffFileFullPath).Extension.ToLower() !=
                    Constant.ImageFileFormat.TIFF.szGetDescription()
                    &&
                    new FileInfo(p_sTiffFileFullPath).Extension.ToLower() !=
                    Constant.ImageFileFormat.TIF.szGetDescription())
                {
                    throw new Exception(
                        "------------- EXCEPTION IN WCF GetPageCountFromTiffFullPath EXCEPTION: [ The Extension of the file is not supported [" +
                        p_sTiffFileFullPath + "]. Only Tif file are supported.]");
                }
                {
                    LicenseGdPicture();
                    int m_ImageID;
                    m_ImageID = m_oGdPictureImaging.TiffCreateMultiPageFromFile(p_sTiffFileFullPath);
                    l_oReturnLong.Value = m_oGdPictureImaging.TiffGetPageCount(m_ImageID);
                    m_oGdPictureImaging.ReleaseGdPictureImage(m_ImageID);
                }
            }
            catch (Exception ex)
            {
                l_oReturnLong =
                    new ReturnLong(
                        "------------- EXCEPTION IN WCF GetPageCountFromTiffFullPath EXCEPTION[" + DateTime.Now + "]",
                        new Exception(ex.Message));
                LogManager.Instance().LogError(l_oReturnLong.FullErrorMessage);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---GetPageCountFromTiffFullPath-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return l_oReturnLong;
        }

        /// <summary>
        ///   Get the path of the pritable version of the file
        /// </summary>
        /// <param name="p_lstDocumentFullPath"> Document to print </param>
        /// <param name="p_oMessageRequest"> The p_o message request. </param>
        /// <returns> ReturnString containing the full path of the printable version of the file </returns>
        public ReturnString GetPrintableVersionOfDocumentFullPath(List<string> p_lstDocumentFullPath,
                                                                  MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo(
                "---GetPrintableVersionOfDocumentFullPath-----p_sDocumentFullPath.Count [" + p_lstDocumentFullPath.Count +
                "]");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            //If the method has been called for a printable version we have to put the file in a temporary directory
            string temporaryDirectory = Treatments.CreateTemporaryDirectory();

            //Convert all documents to pdf
            ReturnString l_oReturnString = new ReturnString();
            List<string> temporaryPdfFiles = new List<string>();
            foreach (var l_oOneFileName in p_lstDocumentFullPath)
            {
                string temporaryPdfFile = Path.Combine(temporaryDirectory, Path.GetFileName(l_oOneFileName));
                var result = MergeDocumentFullPathInPdf(l_oOneFileName, temporaryPdfFile, p_oMessageRequest);
                if (result != null)
                    temporaryPdfFiles.Add(result.Value);
            }

            //Merge all pdf documents to one file
            string l_sFinalFileName = DateTime.Now.ToString("yyyyMMddhhmmssfff") +
                                      Constant.DocumentFileFormat.PDF.szGetDescription();

            string l_sDestinationFileFullPath = Path.Combine(temporaryDirectory, l_sFinalFileName);
            MergePdfFiles(l_sDestinationFileFullPath, temporaryPdfFiles);
            l_oReturnString.Value = l_sDestinationFileFullPath;

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---GetPrintableVersionOfDocumentFullPath-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return l_oReturnString;
        }

        /// <summary>
        ///   Retrieve a part of a source document by its document name
        /// </summary>
        /// <param name="p_sDocumentName"> The name of the thumbnail document </param>
        /// <param name="p_iUserId"> The user identifier </param>
        /// <param name="p_iStartPage"> The first page to retrive </param>
        /// <param name="p_iEndPage"> the last page to retrieve </param>
        /// <returns> The ReturnByte object containing al necessary informations </returns>
        public ReturnDoubleValue GetImportDocumentByFileName(string p_sDocumentName, long p_iUserId, int p_iStartPage,
                                                             int p_iEndPage, MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo(
                "------------- GetImportDocumentByFileName-----p_sDocumentThumbName[" + p_sDocumentName +
                "]--p_iUserId[" + p_iUserId + "]--------------");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);
            ReturnDoubleValue l_oReturnDoubleValue = null;
            string l_sImportDocument = GetImportDocumentFullPath(p_sDocumentName, p_iUserId);
            if (Directory.Exists(l_sImportDocument))
            {
                //Directory
                l_oReturnDoubleValue = new ReturnDoubleValue(null, 0)
                                           {
                                               SecondValue = 0 //todo: set number of files
                                           };
                l_oReturnDoubleValue.Value = GetIconDataByFolderName(l_sImportDocument);
            }
            else
            {
                LogManager.Instance().LogInfo(
                    "------------- GetImportDocumentByFileName-----Calling method GetDocumentByFullPath");
                l_oReturnDoubleValue = GetDocumentByFullPath(l_sImportDocument, p_iStartPage, p_iEndPage,
                                                             p_oMessageRequest, true, p_iUserId, string.Empty);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---GetImportDocumentByFileName-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return l_oReturnDoubleValue;
        }

        /// <summary>
        ///   Return the complete file as byte array
        /// </summary>
        /// <param name="p_sFullPathFileNameToReturn"> </param>
        /// <param name="p_oMessageRequest"> </param>
        /// <param name="p_lUserId"> </param>
        /// <returns> </returns>
        public ReturnDoubleValue GetFileByFullPath(string p_sFullPathFileNameToReturn, MessageRequest p_oMessageRequest,
                                                   long p_lUserId)
        {
            ReturnDoubleValue l_oReturnDoubleValue = new ReturnDoubleValue(null, 0);
            Treatments.CheckApplicationRequestKey(p_oMessageRequest);
            l_oReturnDoubleValue.Value = File.ReadAllBytes(p_sFullPathFileNameToReturn);
            return l_oReturnDoubleValue;
        }

        /// <summary>
        ///   Return a part of a document as a byte array
        /// </summary>
        /// <param name="p_sFullPathFileNameToReturn"> Full path of the file </param>
        /// <param name="p_iStartPage"> The first page to retrive </param>
        /// <param name="p_iEndPage"> the last page to retrieve </param>
        /// <param name="p_oMessageRequest"> The p_o message request. </param>
        /// <param name="p_bImport"> Are we in import mode or not </param>
        /// <param name="p_lUserId"> USer Identifier </param>
        /// <param name="p_sVersion"> The P_S version. </param>
        /// <returns> The byte array pf the file </returns>
        public ReturnDoubleValue GetDocumentByFullPath(string p_sFullPathFileNameToReturn, int p_iStartPage,
                                                       int p_iEndPage, MessageRequest p_oMessageRequest, bool p_bImport,
                                                       long p_lUserId, string p_sVersion)
        {
            ReturnDoubleValue l_oReturnDoubleValue = new ReturnDoubleValue(null, 0);

            try
            {
                Treatments.CheckApplicationRequestKey(p_oMessageRequest);
                var l_oFileToReturnInfo = new FileInfo(p_sFullPathFileNameToReturn);
                if (!l_oFileToReturnInfo.Exists)
                {
                    LogManager.Instance().LogInfo(p_lUserId +
                                                  "-----------------------------GetDocumentByFullPath----- This file [" +
                                                  l_oFileToReturnInfo.FullName +
                                                  "] does not exists--------------");
                    var l_oReturnDoubleValueError =
                        new ReturnDoubleValue("Exception in GetDocumentByFullPath. The file [" +
                                              l_oFileToReturnInfo.FullName + "] does not exists")
                            {ErrorCode = (int) ReturnObject.ErrorCodes.FileNotFound,};
                    return l_oReturnDoubleValueError;
                }

                LogManager.ConfigFile(
                    ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
                LogManager.Instance().LogInfo(string.Empty);
                LogManager.Instance().LogInfo(p_lUserId +
                                              "WFC SERVICE CALLED --------------------------");
                LogManager.Instance().LogInfo(p_lUserId +
                                              "------------- GetDocumentByFullPath-----p_sFullPathFileName[" +
                                              p_sFullPathFileNameToReturn + "]--p_iStartPage[" +
                                              p_iStartPage + "]--p_iEndPage[" + p_iEndPage +
                                              "]--------------");

                l_oReturnDoubleValue = new ReturnDoubleValue(null, 0)
                                           {
                                               SecondValue =
                                                   GetNumberOfPageInDocument(
                                                       new FileInfo(l_oFileToReturnInfo.FullName), true)
                                           };


                // Checking the parameter in the web.config file
                //UseCache tells the application if it has to use the cache process or not
                bool l_bFileInCacheAlreadyExists = false;
                string l_oCacheFileFinalDirectory = string.Empty;
                string l_sCacheFileFinalFileNameFullPath = string.Empty;
                if (CacheManager.CacheEnabled)
                {
                    //Preparing a temporary directory and Constructing the path file of the file that will be generated
                    l_oCacheFileFinalDirectory = CacheManager.GetUserCacheDirectory(p_bImport, p_lUserId);

                    if (!string.IsNullOrEmpty(p_sVersion))
                    {
                        l_sCacheFileFinalFileNameFullPath = Path.Combine(l_oCacheFileFinalDirectory,
                                                                         p_sVersion + "_" +
                                                                         (p_iStartPage - 1).ToString("00000") + "_" +
                                                                         Path.GetFileName(p_sFullPathFileNameToReturn) +
                                                                         Constant.ImageFileFormat.JPG.szGetDescription());
                    }
                    else
                    {
                        l_sCacheFileFinalFileNameFullPath = Path.Combine(l_oCacheFileFinalDirectory,
                                                                         (p_iStartPage - 1).ToString("00000") + "_" +
                                                                         Path.GetFileName(p_sFullPathFileNameToReturn) +
                                                                         Constant.ImageFileFormat.JPG.szGetDescription());
                    }
                    l_bFileInCacheAlreadyExists = File.Exists(l_sCacheFileFinalFileNameFullPath);
                }

                //If file doesn't exist in cache and the cache is not enabled and no xls ext
                if (CacheManager.CacheEnabled == false || l_bFileInCacheAlreadyExists == false ||
                    l_oFileToReturnInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.XLS.szGetDescription()))
                {
                    //Creating temporary directory to avoid multiple access to the same file
                    string temporaryFileUniqueDirectory = Treatments.CreateTemporaryDirectory();
                    string temporaryUniqueFileNameFullPath = string.Empty;
                    if (!string.IsNullOrEmpty(p_sVersion))
                    {
                        temporaryUniqueFileNameFullPath = Path.Combine(temporaryFileUniqueDirectory,
                                                                       p_sVersion + "_" +
                                                                       (p_iStartPage - 1).ToString("00000") + "_" +
                                                                       Path.GetFileName(p_sFullPathFileNameToReturn) +
                                                                       Constant.ImageFileFormat.JPG.szGetDescription());
                    }
                    else
                    {
                        temporaryUniqueFileNameFullPath = Path.Combine(temporaryFileUniqueDirectory,
                                                                       (p_iStartPage - 1).ToString("00000") + "_" +
                                                                       Path.GetFileName(p_sFullPathFileNameToReturn) +
                                                                       Constant.ImageFileFormat.JPG.szGetDescription());
                    }

                    try
                    {
                        LogManager.Instance().LogInfo(p_lUserId + "----- File " +
                                                      l_oFileToReturnInfo.FullName +
                                                      " does not exists in cache ------");


                        if (
                            l_oFileToReturnInfo.Extension.ToLower().Equals(
                                Constant.ImageFileFormat.BMP.szGetDescription()))
                        {
                            #region BMP

                            using (Treatments trt = new Treatments())
                            {
                                trt.SaveToJpeg(temporaryUniqueFileNameFullPath, l_oFileToReturnInfo.FullName,
                                               int.Parse(ConfigurationManager.AppSettings.Get("QualityAfterResize")));
                            }

                            #endregion
                        }
                        if (l_oFileToReturnInfo.Extension.ToLower().Equals(
                            Constant.ImageFileFormat.JPEG.szGetDescription())
                            ||
                            l_oFileToReturnInfo.Extension.ToLower().Equals(
                                Constant.ImageFileFormat.JPG.szGetDescription())
                            ||
                            l_oFileToReturnInfo.Extension.ToLower().Equals(
                                Constant.ImageFileFormat.PNG.szGetDescription()))
                        {
                            #region JPG/JPEG/PNG

                            int m_iImageID = 0;
                            try
                            {
                                m_iImageID =
                                    m_oGdPictureImaging.CreateGdPictureImageFromFile(l_oFileToReturnInfo.FullName);
                                m_iHeigth = m_oGdPictureImaging.GetHeight(m_iImageID);
                                m_iWidth = m_oGdPictureImaging.GetWidth(m_iImageID);
                                m_oGdPictureImaging.ReleaseGdPictureImage(m_iImageID);
                                var l_oSize = GetSizeImage(m_iWidth, m_iHeigth,
                                                           int.Parse(
                                                               ConfigurationManager.AppSettings.Get("MaxWidthResize")));
                                if (m_iHeigth > l_oSize.Height || m_iWidth > l_oSize.Width)
                                {
                                    Treatments.ResizeImage(l_oFileToReturnInfo.FullName,
                                                           temporaryUniqueFileNameFullPath,
                                                           l_oSize.Width,
                                                           l_oSize.Height,
                                                           true);
                                }
                                else
                                {
                                    File.Copy(l_oFileToReturnInfo.FullName, temporaryUniqueFileNameFullPath, true);
                                }
                            }
                            catch (Exception ex)
                            {
                                throw ex;
                            }
                            finally
                            {
                                if (m_iImageID > 0)
                                    m_oGdPictureImaging.ReleaseGdPictureImage(m_iImageID);
                            }

                            #endregion
                        }
                        if (l_oFileToReturnInfo.Extension.ToLower().Equals(
                            Constant.DocumentFileFormat.DOC.szGetDescription())
                            ||
                            l_oFileToReturnInfo.Extension.ToLower().Equals(
                                Constant.DocumentFileFormat.DOCX.szGetDescription())
                            ||
                            l_oFileToReturnInfo.Extension.ToLower().Equals(
                                Constant.DocumentFileFormat.RTF.szGetDescription()))
                        {
                            #region DOC / RTF

                            #region Aspose licencing

                            var wordLicense = new License();
                            wordLicense.SetLicense("Aspose.Total.lic");

                            #endregion

                            var l_oWordDocument = new Aspose.Words.Document(l_oFileToReturnInfo.FullName);
                            var l_oImageOptionsNew = new ImageOptions
                                                         {
                                                             JpegQuality =
                                                                 int.Parse(
                                                                     ConfigurationManager.AppSettings.Get("ImageQuality")),
                                                             Resolution =
                                                                 float.Parse(
                                                                     ConfigurationManager.AppSettings.Get(
                                                                         "ImageResolution"))
                                                         };
                            for (var i = 0; i < l_oWordDocument.PageCount; i++)
                            {
                                string temporaryfile = string.Empty;
                                if (!string.IsNullOrEmpty(p_sVersion))
                                {
                                    temporaryfile = Path.Combine(temporaryFileUniqueDirectory,
                                                                 p_sVersion + "_" + i.ToString("00000") + "_" +
                                                                 Path.GetFileName(l_oFileToReturnInfo.FullName) +
                                                                 Constant.ImageFileFormat.JPG.szGetDescription());
                                }
                                else
                                {
                                    temporaryfile = Path.Combine(temporaryFileUniqueDirectory,
                                                                 i.ToString("00000") + "_" +
                                                                 Path.GetFileName(l_oFileToReturnInfo.FullName) +
                                                                 Constant.ImageFileFormat.JPG.szGetDescription());
                                }

                                l_oWordDocument.SaveToImage(i, 1, temporaryfile, l_oImageOptionsNew);
                            }

                            #endregion
                        }
                        if (
                            l_oFileToReturnInfo.Extension.ToLower().Equals(
                                Constant.DocumentFileFormat.TXT.szGetDescription()))
                        {
                            #region TXT

                            if (!File.Exists(Path.Combine(temporaryFileUniqueDirectory, l_oFileToReturnInfo.FullName) +
                                             Constant.DocumentFileFormat.PDF.szGetDescription()))
                            {
                                LogManager.Instance().LogInfo(p_lUserId +
                                                              "---------------------------- Converting doc/rtf file into pdf [" +
                                                              l_oFileToReturnInfo.FullName + "]");

                                //Converting the word file
                                var l_sGuid = Guid.NewGuid().ToString("N");
                                LogManager.Instance().LogDebug(
                                    "---------------------------- Saving new pdf file to [" +
                                    Path.Combine(temporaryFileUniqueDirectory, l_sGuid) +
                                    Constant.DocumentFileFormat.PDF.szGetDescription() + "]");
                                ConvertTextToPdf(l_oFileToReturnInfo.FullName,
                                                 Path.Combine(temporaryFileUniqueDirectory,
                                                              Path.GetFileName(l_oFileToReturnInfo.FullName)) +
                                                 Constant.DocumentFileFormat.PDF.szGetDescription());
                            }

                            #region SolidFramework

                            var l_iPageRange = Convert.ToString(p_iStartPage - 1);

                            var l_sInputFile = Path.Combine(temporaryFileUniqueDirectory,
                                                            Path.GetFileName(l_oFileToReturnInfo.FullName) +
                                                            Constant.DocumentFileFormat.PDF.szGetDescription());
                            using (Treatments l_oPDFtoImage = new Treatments())
                            {
                                l_oPDFtoImage.DoConversion(l_sInputFile, null, temporaryUniqueFileNameFullPath,
                                                           int.Parse(
                                                               ConfigurationManager.AppSettings.Get("DoConversionHigh")),
                                                           l_iPageRange, Treatments.ImageType.Jpg);
                            }

                            #endregion

                            #endregion
                        }
                        if (l_oFileToReturnInfo.Extension.ToLower().Equals(
                            Constant.DocumentFileFormat.XLSX.szGetDescription())
                            ||
                            l_oFileToReturnInfo.Extension.ToLower().Equals(
                                Constant.DocumentFileFormat.XLS.szGetDescription()))
                        {
                            #region XLS

                            #region Aspose licencing

                            var xlsLicense = new Aspose.Cells.License();
                            xlsLicense.SetLicense("Aspose.Total.lic");

                            #endregion

                            var l_oWorkbook = new Workbook(l_oFileToReturnInfo.FullName);

                            //Open template
                            var l_oImgOptions = new ImageOrPrintOptions
                                                    {
                                                        ImageFormat = ImageFormat.Jpeg,
                                                        IsImageFitToPage = true,
                                                    };

                            var l_iTotalPages = 0;

                            for (var i = 0; i < l_oWorkbook.Worksheets.Count; i++)
                            {
                                var sheet = l_oWorkbook.Worksheets[i];
                                //To remove the white border around the image.
                                //Hide the sheet gridlines
                                sheet.IsGridlinesVisible = true;

                                //Setting the orientation to Landscape
                                sheet.PageSetup.Orientation = PageOrientationType.Landscape;

                                //Setting the paper size Tabloid
                                sheet.PageSetup.PaperSize = PaperSizeType.PaperTabloid;

                                //Setting the print quality of the worksheet to 1200 dpi
                                sheet.PageSetup.PrintQuality = 1200;

                                var sheetRender = new SheetRender(sheet, l_oImgOptions);
                                l_iTotalPages = l_iTotalPages + sheetRender.PageCount;
                            }

                            var l_iPreviousTotalPage = 0;
                            for (var i = 0; i < l_oWorkbook.Worksheets.Count; i++)
                            {
                                var sheet = l_oWorkbook.Worksheets[i];
                                sheet.IsGridlinesVisible = true;

                                //Setting the orientation to Portrait
                                sheet.PageSetup.Orientation = PageOrientationType.Landscape;

                                //Setting the paper size to Tabloid
                                sheet.PageSetup.PaperSize = PaperSizeType.PaperTabloid;

                                //Setting the print quality of the worksheet to 1200 dpi
                                sheet.PageSetup.PrintQuality = 1200;

                                var sheetRender = new SheetRender(sheet, l_oImgOptions);

                                l_iPreviousTotalPage = l_iPreviousTotalPage + sheetRender.PageCount;

                                if (p_iStartPage <= l_iPreviousTotalPage)
                                {
                                    string l_sWorksheetImage = string.Empty;
                                    if (!string.IsNullOrEmpty(p_sVersion))
                                    {
                                        l_sWorksheetImage = Path.Combine(temporaryFileUniqueDirectory,
                                                                         string.Format("{0}_{1}{2}",
                                                                                       p_sVersion + "_" +
                                                                                       (p_iStartPage - 1).ToString("00000"),
                                                                                       Path.GetFileName(l_oFileToReturnInfo.FullName),
                                                                                       Constant.ImageFileFormat.JPG.szGetDescription()));
                                    }
                                    else
                                    {
                                        l_sWorksheetImage = Path.Combine(temporaryFileUniqueDirectory,
                                                                         string.Format("{0}_{1}{2}",
                                                                                       (p_iStartPage - 1).ToString("00000"),
                                                                                       Path.GetFileName(l_oFileToReturnInfo.FullName),
                                                                                       Constant.ImageFileFormat.JPG.szGetDescription()));
                                    }

                                    if (!File.Exists(l_sWorksheetImage))
                                    {
                                        sheetRender.ToImage(
                                            sheetRender.PageCount - (l_iPreviousTotalPage - p_iStartPage) - 1,
                                            l_sWorksheetImage);
                                    }
                                    break;
                                }
                            }

                            #endregion
                        }
                        if (
                            l_oFileToReturnInfo.Extension.ToLower().Equals(
                                Constant.DocumentFileFormat.PPT.szGetDescription()))
                        {
                            #region PPT

                            #region Aspose licencing

                            var slideLicense = new Aspose.Slides.License();
                            slideLicense.SetLicense("Aspose.Total.lic");

                            #endregion

                            var l_oPresentation = new Presentation(l_oFileToReturnInfo.FullName);
                            for (var i = 0; i < l_oPresentation.Slides.Count; i++)
                            {
                                var l_oThumbPpt =
                                    l_oPresentation.Slides[i].GetThumbnail(
                                        new Size(int.Parse(ConfigurationManager.AppSettings.Get("PPTImageWidth")),
                                                 int.Parse(ConfigurationManager.AppSettings.Get("PPTImageHeigth"))));

                                string thumbPath = string.Empty;
                                if (!string.IsNullOrEmpty(p_sVersion))
                                {
                                    thumbPath = Path.Combine(temporaryFileUniqueDirectory,
                                                             p_sVersion + "_" + i.ToString("00000") + "_" +
                                                             Path.GetFileName(l_oFileToReturnInfo.FullName) +
                                                             Constant.ImageFileFormat.JPG.szGetDescription());
                                }
                                else
                                {
                                    thumbPath = Path.Combine(temporaryFileUniqueDirectory,
                                                             i.ToString("00000") + "_" +
                                                             Path.GetFileName(l_oFileToReturnInfo.FullName) +
                                                             Constant.ImageFileFormat.JPG.szGetDescription());
                                }

                                l_oThumbPpt.Save(thumbPath, ImageFormat.Jpeg);
                            }

                            #endregion
                        }
                        if (
                            l_oFileToReturnInfo.Extension.ToLower().Equals(
                                Constant.DocumentFileFormat.PDF.szGetDescription()))
                        {
                            #region PDF

                            var l_bDoUseSolidFramework = true;

                            // we create a reader for a the specified document
                            PdfReader l_oReader = null;
                            int nbAttemptCount = 0;
                            while (true)
                            {
                                try
                                {
                                    //Create instance for the PDF reader
                                    l_oReader = new PdfReader(l_oFileToReturnInfo.FullName);
                                    break;
                                }
                                catch (Exception ex)
                                {
                                    nbAttemptCount++;
                                    LogManager.Instance().LogError(p_lUserId + "ex new pdfreader" +
                                                                   ex.Message + "\n" + ex.StackTrace);

                                    Thread.Sleep(500);
                                    if (nbAttemptCount == 50)
                                    {
                                        throw ex;
                                    }
                                }
                            }

                            // we retrieve the total number of pages
                            if (l_oReturnDoubleValue.SecondValue > 1)
                            {
                                LogManager.Instance().LogInfo(p_lUserId +
                                                              "---Extracting first page from multiple pdf pages-----------------" +
                                                              p_lUserId);

                                string l_sTemporaryFilenameFullPath = string.Empty;
                                if (!string.IsNullOrEmpty(p_sVersion))
                                {
                                    l_sTemporaryFilenameFullPath = Path.Combine(temporaryFileUniqueDirectory,
                                                                                p_sVersion + "_" + "00000_" +
                                                                                Path.GetFileName(
                                                                                    l_oFileToReturnInfo.FullName));
                                }
                                else
                                {
                                    l_sTemporaryFilenameFullPath = Path.Combine(temporaryFileUniqueDirectory,
                                                                                "00000_" +
                                                                                Path.GetFileName(
                                                                                    l_oFileToReturnInfo.FullName));
                                }


                                try
                                {
                                    LogManager.Instance().LogInfo(p_lUserId +
                                                                  "---Treatments.ExtractPdfPage(l_oReader, p_iStartPage, l_sFilenameFullPath, l_oFileInfo.FullName);-----------------" +
                                                                  p_lUserId);
                                    Treatments.ExtractPdfPage(l_oReader, p_iStartPage, l_sTemporaryFilenameFullPath,
                                                              l_oFileToReturnInfo.FullName);
                                    p_sFullPathFileNameToReturn = l_sTemporaryFilenameFullPath;
                                }
                                catch
                                {
                                    //In this case Itextsharp did not manage to extract the page of the multipage pdf file. So we will use soldiframework to do it.
                                    //we try not using solidfrfaamework for the pdf file because the process to convert is long for big pdf file.
                                    string l_iPageRange = null;
                                    if (l_oReturnDoubleValue.SecondValue > 1)
                                    {
                                        l_iPageRange = Convert.ToString(p_iStartPage - 1);
                                    }

                                    using (Treatments l_oPDFtoImagecatch = new Treatments())
                                    {
                                        if (!File.Exists(temporaryUniqueFileNameFullPath))
                                        {
                                            try
                                            {
                                                l_oPDFtoImagecatch.DoConversion(p_sFullPathFileNameToReturn, null,
                                                                                temporaryUniqueFileNameFullPath,
                                                                                int.Parse(
                                                                                    ConfigurationManager.AppSettings.Get
                                                                                        (
                                                                                            "DoConversionHigh")),
                                                                                l_iPageRange,
                                                                                Treatments.ImageType.Jpg);
                                            }
                                            catch (Exception)
                                            {
                                                LogManager.Instance().LogInfo(p_lUserId +
                                                                              "---erreur lors du DoConversionHigh-----------------");
                                                l_oPDFtoImagecatch.DoConversion(p_sFullPathFileNameToReturn, null,
                                                                                temporaryUniqueFileNameFullPath,
                                                                                int.Parse(
                                                                                    ConfigurationManager.AppSettings.Get
                                                                                        (
                                                                                            "DoConversionLow")),
                                                                                l_iPageRange,
                                                                                Treatments.ImageType.Jpg);
                                            }
                                        }
                                    }
                                    l_bDoUseSolidFramework = false;
                                }
                            }

                            l_oReader.Close();

                            #region SolidFramework

                            LogManager.Instance().LogInfo(p_lUserId +
                                                          "--------------------------------- SolidFramework conversion from pdf[" +
                                                          p_sFullPathFileNameToReturn +
                                                          "]-------------------------- ");
                            using (Treatments l_oPDFtoImage = new Treatments())
                            {
                                if (l_bDoUseSolidFramework)
                                {
                                    if (!File.Exists(temporaryUniqueFileNameFullPath))
                                    {
                                        try
                                        {
                                            l_oPDFtoImage.DoConversion(p_sFullPathFileNameToReturn, null,
                                                                       temporaryUniqueFileNameFullPath,
                                                                       int.Parse(
                                                                           ConfigurationManager.AppSettings.Get(
                                                                               "DoConversionHigh")),
                                                                       "0", Treatments.ImageType.Jpg);
                                        }
                                        catch (Exception ex)
                                        {
                                            LogManager.Instance().LogError(p_lUserId +
                                                                           "--------------------------------- DoConversion[" +
                                                                           ex.Message +
                                                                           "]--------------------------- ");
                                            l_oPDFtoImage.DoConversion(p_sFullPathFileNameToReturn, null,
                                                                       temporaryUniqueFileNameFullPath,
                                                                       int.Parse(
                                                                           ConfigurationManager.AppSettings.Get(
                                                                               "DoConversionLow")),
                                                                       "0", Treatments.ImageType.Jpg);
                                        }
                                    }
                                }
                            }

                            #endregion

                            #endregion
                        }
                        if (
                            l_oFileToReturnInfo.Extension.ToLower().Equals(
                                Constant.ImageFileFormat.GIF.szGetDescription()))
                        {
                            #region GIF

                            int m_iImageID =
                                m_oGdPictureImaging.CreateGdPictureImageFromFile(l_oFileToReturnInfo.FullName);
                            m_oGdPictureImaging.SaveAsJPEG(m_iImageID, temporaryUniqueFileNameFullPath);

                            m_iHeigth = m_oGdPictureImaging.GetHeight(m_iImageID);
                            m_iWidth = m_oGdPictureImaging.GetWidth(m_iImageID);

                            m_oGdPictureImaging.ReleaseGdPictureImage(m_iImageID);

                            var l_oSize = GetSizeImage(m_iWidth, m_iHeigth,
                                                       int.Parse(ConfigurationManager.AppSettings.Get("MaxWidthResize")));
                            if (m_iHeigth > l_oSize.Height || m_iWidth > l_oSize.Width)
                            {
                                Treatments.ResizeImage(
                                    temporaryUniqueFileNameFullPath,
                                    temporaryUniqueFileNameFullPath,
                                    l_oSize.Width,
                                    l_oSize.Height,
                                    true
                                    );
                            }

                            #endregion
                        }
                        if (l_oFileToReturnInfo.Extension.ToLower().Equals(
                            Constant.ImageFileFormat.TIF.szGetDescription())
                            ||
                            l_oFileToReturnInfo.Extension.ToLower().Equals(
                                Constant.ImageFileFormat.TIFF.szGetDescription()))
                        {
                            #region TIFF/TIF

                            using (Treatments trt = new Treatments())
                            {
                                try
                                {
                                    trt.SaveTiffAsJpeg(l_oFileToReturnInfo.FullName, temporaryUniqueFileNameFullPath,
                                                       p_iStartPage);
                                }
                                catch
                                {
                                    trt.SaveToJpeg(temporaryUniqueFileNameFullPath, l_oFileToReturnInfo.FullName,
                                                   int.Parse(ConfigurationManager.AppSettings.Get("QualityAfterResize")));
                                }
                            }

                            #endregion
                        }

                        #region Image Resizing

                        try
                        {
                            if (File.Exists(temporaryUniqueFileNameFullPath))
                            {
                                if (IsFileTooLarge(new FileInfo(temporaryUniqueFileNameFullPath),
                                                   int.Parse(ConfigurationManager.AppSettings.Get("MaxWeigthResizeKo"))))
                                {
                                    using (Treatments trt = new Treatments())
                                    {
                                        trt.SaveToJpeg(temporaryUniqueFileNameFullPath, temporaryUniqueFileNameFullPath,
                                                       int.Parse(
                                                           ConfigurationManager.AppSettings.Get("QualityAfterResize")));
                                    }
                                }
                            }
                        }
                        catch (Exception exSaveJpeg)
                        {
                            LogManager.Instance().LogError(p_lUserId +
                                                           "--Image Resizing----------------SaveJpeg " +
                                                           exSaveJpeg.Message);
                        }

                        #endregion

                        #region Image returning

                        int imageID = 0;
                        try
                        {
                            byte[] l_oBinary = null;
                            int l_oBytesRead = 0;
                            imageID = m_oGdPictureImaging.CreateGdPictureImageFromFile(temporaryUniqueFileNameFullPath);
                            m_oGdPictureImaging.SaveAsByteArray(imageID, ref l_oBinary, ref l_oBytesRead,
                                                                m_oGdPictureImaging.GetDocumentFormatFromFile(
                                                                    temporaryUniqueFileNameFullPath), 0);

                            l_oReturnDoubleValue.Value = l_oBinary;
                        }
                        catch (Exception exFileStream)
                        {
                            LogManager.Instance().LogError(p_lUserId +
                                                           "---new filestream-----------------" +
                                                           exFileStream.Message);
                        }
                        finally
                        {
                            if (imageID > 0)
                                m_oGdPictureImaging.ReleaseGdPictureImage(imageID);
                        }

                        #endregion

                        #region Cache handling

                        if (CacheManager.CacheEnabled)
                        {
                            try
                            {
                                if (!File.Exists(l_sCacheFileFinalFileNameFullPath))
                                {
                                    var l_oDirectoryOfUniqueGeneratedFile =
                                        new DirectoryInfo(temporaryFileUniqueDirectory);
                                    if (l_oDirectoryOfUniqueGeneratedFile.Exists)
                                    {
                                        var l_lstFileNamesToPutInCache =
                                            l_oDirectoryOfUniqueGeneratedFile.GetFiles("*" +
                                                                                       Constant.ImageFileFormat.JPG.
                                                                                           szGetDescription());
                                        // Copy the files and overwrite destination files if they already exist.
                                        foreach (var l_sOneJpegFileToPutInCache in l_lstFileNamesToPutInCache)
                                        {
                                            // Use static Path methods to extract only the file name from the path.
                                            File.Copy(l_sOneJpegFileToPutInCache.FullName,
                                                      Path.Combine(l_oCacheFileFinalDirectory,
                                                                   Path.GetFileName(l_sOneJpegFileToPutInCache.FullName)),
                                                      true);
                                        }
                                    }
                                }
                            }
                            catch (Exception exCopy)
                            {
                                LogManager.Instance().LogError(p_lUserId +
                                                               "---generating file cache failed----------------" +
                                                               exCopy.Message);
                            }
                        }

                        #endregion
                    }
                    catch (Exception ex)
                    {
                        l_oReturnDoubleValue =
                            new ReturnDoubleValue(
                                "---------------------------- EXCEPTION IN WCF GetDocumentByFullPath EXCEPTION[" +
                                DateTime.Now + "]",
                                new Exception(ex.Message + "ex.inner" + ex.InnerException + "ex.stacktrace" +
                                              ex.StackTrace));
                        l_oReturnDoubleValue.ErrorMessage =
                            "---------------------------- EXCEPTION IN WCF GetDocumentByFullPath EXCEPTION[" +
                            ex.Message + "]" + DateTime.Now;
                        l_oReturnDoubleValue.ApplicationException = new Exception(ex.Message);
                        using (
                            var l_oFs =
                                new FileStream(
                                    Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Icones\\erreur.jpg"),
                                    FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                        {
                            var l_oBinary = StreamtoByteArray(l_oFs);
                            l_oFs.Dispose();
                            l_oFs.Close();
                            l_oReturnDoubleValue.Value = l_oBinary;
                        }
                        l_oReturnDoubleValue.ErrorCode = (int) ReturnObject.ErrorCodes.CorruptedFile;

                        LogManager.Instance().LogError("user id [" + p_lUserId +
                                                       "] exception dans le if du cache : " + ex.Message +
                                                       "ex.inner" + ex.InnerException + "ex.stacktrace" +
                                                       ex.StackTrace);
                    }
                    finally
                    {
                        Treatments.DeleteDirectory(temporaryFileUniqueDirectory);
                    }
                }
                else
                {
                    //The file already exist in the cache directory
                    int imageID = 0;
                    try
                    {
                        byte[] l_oBinary = null;
                        int l_oBytesRead = 0;
                        imageID = m_oGdPictureImaging.CreateGdPictureImageFromFile(l_sCacheFileFinalFileNameFullPath);
                        m_oGdPictureImaging.SaveAsByteArray(imageID, ref l_oBinary, ref l_oBytesRead,
                                                            m_oGdPictureImaging.GetDocumentFormatFromFile(
                                                                l_sCacheFileFinalFileNameFullPath),
                                                            int.Parse(
                                                                ConfigurationManager.AppSettings.Get(
                                                                    "QualityAfterResize")));

                        l_oReturnDoubleValue.Value = l_oBinary;
                    }
                    catch (Exception ex)
                    {
                        LogManager.Instance().LogError(p_lUserId + "---else du cache-----------------" +
                                                       ex.Message);
                    }
                    finally
                    {
                        if (imageID > 0)
                            m_oGdPictureImaging.ReleaseGdPictureImage(imageID);
                    }
                }
            }
            catch (Exception ex)
            {
                l_oReturnDoubleValue =
                    new ReturnDoubleValue(
                        "---------------------------- EXCEPTION IN WCF GetDocumentByFullPath EXCEPTION[" + DateTime.Now +
                        "]",
                        new Exception(ex.Message + "ex.inner" + ex.InnerException + "ex.stacktrace" + ex.StackTrace));
                l_oReturnDoubleValue.ErrorMessage =
                    "---------------------------- EXCEPTION IN WCF GetDocumentByFullPath EXCEPTION[" + ex.Message + "]" +
                    DateTime.Now;
            }


            LogManager.Instance().LogInfo(p_lUserId + "---GetDocumentByFullPath-----------------");
            LogManager.Instance().LogInfo(p_lUserId + "END OF WFC SERVICE CALL ---------------------");

            return l_oReturnDoubleValue;
        }

        /// <summary>
        ///   Split a PDF file in one page pdf file
        /// </summary>
        /// <param name="p_sFileName"> The name of the file </param>
        /// <param name="p_lUserId"> The User identifier </param>
        /// <param name="p_bImport"> </param>
        public void GeneratePdfPages(string p_sFileName, long p_lUserId, bool p_bImport,
                                     MessageRequest p_oMessageRequest)
        {
            Treatments.CheckApplicationRequestKey(p_oMessageRequest);
            //NetBay.Core.Log.LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            //NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
            //NetBay.Core.Log.LogManager.Instance().LogInfo(p_lUserId + "---------------------------Call of GeneratePdfPages");

            //var l_sOutputdirectory = string.Empty;

            //if (Path.GetExtension(p_sFileName).ToLower().Equals(Constant.DocumentFileFormat.PDF.szGetDescription()))
            //{
            //    if (p_bImport)
            //    {
            //        l_sOutputdirectory = Path.GetFullPath(GetUserCacheDirectory(p_sFileName, true, p_lUserId));
            //        p_sFileName = GetImportDocumentFullPath(p_sFileName, p_lUserId);
            //    }
            //    else
            //    {
            //        l_sOutputdirectory = Path.GetFullPath(GetUserCacheDirectory(Path.GetFileName(p_sFileName), false, 0));
            //    }

            //    var l_oOriginalDateTime = new FileInfo(p_sFileName).LastWriteTime;
            //    var l_sOriginalFileName = p_sFileName;

            //    Treatments.CheckDirectory(
            //        Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory"), p_lUserId + "\\active\\" ));
            //    var l_sDuplicatedFile = Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory"), p_lUserId + "\\active\\" +  Path.GetFileName(p_sFileName));

            //    if (File.Exists(p_sFileName))
            //    {

            //        if (l_oOriginalDateTime != new FileInfo(l_sOriginalFileName).LastWriteTime)
            //        {
            //            File.Delete(l_sDuplicatedFile);
            //            File.Copy(p_sFileName, l_sDuplicatedFile);

            //            p_sFileName = l_sDuplicatedFile;


            //            var reader = new PdfReader(p_sFileName);
            //            var l_oDi = new DirectoryInfo(l_sOutputdirectory);
            //            var l_oRgFilesJpg = l_oDi.GetFiles("*.jpg");
            //            var l_oRgFilesPdf = l_oDi.GetFiles("*.pdf");

            //            var l_bFileModified = false;

            //            if (reader.NumberOfPages > 1 && l_oRgFilesPdf.Count() == 0 &&
            //                l_oRgFilesJpg.Count() < reader.NumberOfPages)
            //            {
            //                // we create a reader for a certain document
            //                var l_oReader = new PdfReader(p_sFileName);
            //                // we retrieve the total number of pages
            //                var l_iNumberOfPages = l_oReader.NumberOfPages;

            //                iTextSharp.text.Document l_oDocument;

            //                var l_sFilename = string.Empty;


            //                for (var i = 2; i <= l_iNumberOfPages; i++)
            //                {
            //                    if (
            //                        File.Exists(
            //                            Path.Combine(
            //                                ConfigurationManager.AppSettings.Get("Rio.WCF.Services.InputDirectory"),
            //                                p_lUserId + "\\" + Path.GetFileName(p_sFileName))))
            //                    {

            //                        l_sFilename = Path.Combine(l_sOutputdirectory,
            //                                                   i.ToString("00000") + "_" + Path.GetFileName(p_sFileName));
            //                        // step 1: creation of a document-object
            //                        l_oDocument = new iTextSharp.text.Document(l_oReader.GetPageSizeWithRotation(i));
            //                        // step 2: we create a writer that listens to the document
            //                        var l_oWriter = PdfWriter.GetInstance(l_oDocument,
            //                                                              new FileStream(l_sFilename, FileMode.Create));
            //                        l_oWriter.SetPdfVersion(PdfWriter.PDF_VERSION_1_5);
            //                        l_oWriter.CompressionLevel = PdfStream.BEST_COMPRESSION;
            //                        // step 3: we open the document
            //                        l_oDocument.Open();
            //                        var l_oCb = l_oWriter.DirectContent;
            //                        var l_oPage = l_oWriter.GetImportedPage(l_oReader, i);
            //                        var l_iRotation = l_oReader.GetPageRotation(i);
            //                        if (l_iRotation == 90 || l_iRotation == 270)
            //                        {
            //                            l_oCb.AddTemplate(l_oPage, 0, -1f, 1f, 0, 0,
            //                                              l_oReader.GetPageSizeWithRotation(i).Height);
            //                        }
            //                        else
            //                        {
            //                            l_oCb.AddTemplate(l_oPage, 1f, 0, 0, 1f, 0, 0);
            //                        }
            //                        // step 5: we close the document
            //                        l_oDocument.Close();

            //                        if (l_oOriginalDateTime != new FileInfo(l_sOriginalFileName).LastWriteTime)
            //                        {
            //                            l_oWriter.Close();
            //                            l_bFileModified = true;
            //                            break;
            //                        }
            //                    }
            //                    else
            //                    {
            //                        l_bFileModified = true;
            //                        break;
            //                    }
            //                }

            //                if (l_bFileModified)
            //                {
            //                    try
            //                    {
            //                        Directory.Delete(l_sOutputdirectory, true);
            //                    }
            //                    catch
            //                    {
            //                    }

            //                    if (File.Exists(
            //                        Path.Combine(
            //                            ConfigurationManager.AppSettings.Get("Rio.WCF.Services.InputDirectory"),
            //                            p_lUserId + "\\" + Path.GetFileName(p_sFileName))))
            //                    {
            //                        GeneratePdfPages(Path.GetFileName(l_sOriginalFileName), p_lUserId, p_bImport);
            //                        var l_oTreatment = new Treatments();
            //                        l_oTreatment.CreateThumb(l_sOriginalFileName,
            //                                                 GetThumbDocumentFullPath(
            //                                                     Path.GetFileName(l_sOriginalFileName),
            //                                                     p_lUserId));
            //                    }
            //                }

            //                File.Delete(l_sDuplicatedFile);

            //                Treatments.
            //            }
            //        }
            //    }
            //}

            //NetBay.Core.Log.LogManager.Instance().LogInfo("---------------------------End of Call of GeneratePdfPages");
        }

        /// <summary>
        ///   Returns true if the file already exists
        /// </summary>
        /// <param name="p_sFileName"> File Name </param>
        /// <param name="p_iUserId"> the user identifier </param>
        /// <returns> True if the file already exists </returns>
        public ReturnBoolean ImportFileExists(string p_sFileName, long p_iUserId, MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---ImportFileExists-----p_sFileName[" + p_sFileName +
                                          "]---p_iUserId[" + p_iUserId + "]");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            var l_oReturnBoolean = new ReturnBoolean();

            try
            {
                l_oReturnBoolean.Value = File.Exists(GetImportDocumentFullPath(p_sFileName, p_iUserId));
            }
            catch (Exception ex)
            {
                l_oReturnBoolean =
                    new ReturnBoolean(
                        "------------- EXCEPTION IN WCF ImportFileExists EXCEPTION[" + DateTime.Now + "]",
                        new Exception(ex.Message));
                LogManager.Instance().LogError(l_oReturnBoolean.FullErrorMessage);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---ImportFileExists-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return l_oReturnBoolean;
        }

        /// <summary>
        ///   Returns true if the directory is empty
        /// </summary>
        /// <param name="p_sFileName"> Directory Name </param>
        /// <param name="p_iUserId"> the user identifier </param>
        /// <returns> True if the directory is empty </returns>
        public ReturnBoolean ImportDirectoryIsEmpty(string p_sDirectoryName, long p_iUserId,
                                                    MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---ImportDirectoryIsEmpty-----p_sDirectoryName[" +
                                          p_sDirectoryName + "]---p_iUserId[" + p_iUserId + "]");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            var l_oReturnBoolean = new ReturnBoolean();
            l_oReturnBoolean.Value = false;
            l_oReturnBoolean.IsValid = true;
            try
            {
                var l_oDi = new DirectoryInfo(GetThumbDocumentFullPath(string.Empty, p_iUserId, p_sDirectoryName));
                if (l_oDi.Exists)
                {
                    var l_oRgFiles = l_oDi.GetFiles("*" + Constant.ImageFileFormat.JPG.szGetDescription());
                    l_oReturnBoolean.Value = (l_oRgFiles == null || l_oRgFiles.Length == 0);
                }
            }
            catch (Exception ex)
            {
                l_oReturnBoolean =
                    new ReturnBoolean(
                        "------------- EXCEPTION IN WCF ImportDirectoryIsEmpty EXCEPTION[" + DateTime.Now + "]",
                        new Exception(ex.Message));
                LogManager.Instance().LogError(l_oReturnBoolean.FullErrorMessage);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---ImportDirectoryIsEmpty-----------------");
            LogManager.Instance().LogInfo("END OF WCF SERVICE CALL ---------------------");

            return l_oReturnBoolean;
        }

        /// <summary>
        ///   Move the document to the indexed directory path
        /// </summary>
        /// <param name="p_lstDocument"> Name of the document </param>
        /// <param name="p_lUserId"> The user identifier </param>
        /// <returns> A List of al document that has been moved </returns>
        public List<Document> MoveImportDocument(
            List<Document> p_lstDocument, long p_lUserId, MessageRequest p_oMessageRequest)
        {
            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            lock (m_LockObject)
            {
                LogManager.ConfigFile(
                    ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
                LogManager.Instance().LogInfo(string.Empty);
                LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
                LogManager.Instance().LogInfo("---MoveImportDocument-----p_lstDocument.Count[" +
                                              p_lstDocument.Count + "]---p_lUSerId[" + p_lUserId + "]");

                var l_lstReturnDocument = new List<Document>();

                foreach (var l_oDocument in p_lstDocument)
                {
                    var l_oDocumentReturn = new Document();
                    try
                    {
                        l_oDocumentReturn.Identifier = l_oDocument.Identifier;
                        l_oDocumentReturn.OriginalNameFile = l_oDocument.OriginalNameFile;

                        //Move document
                        Treatments.CheckDirectory(new FileInfo(l_oDocument.RelativePath).DirectoryName);
                        LogManager.Instance().LogDebug(
                            "----------------- Trying to move document from [" +
                            GetImportDocumentFullPath(l_oDocument.ImageName, p_lUserId) + "] to [" +
                            l_oDocument.RelativePath + "]" + DateTime.Now);
                        File.Move(GetImportDocumentFullPath(l_oDocument.ImageName, p_lUserId), l_oDocument.RelativePath);
                        LogManager.Instance().LogInfo("----------------- File moved from [" +
                                                      GetImportDocumentFullPath(l_oDocument.ImageName,
                                                                                p_lUserId) + "] to [" +
                                                      l_oDocument.RelativePath + "]" + DateTime.Now);

                        //Move thumbnail
                        Treatments.CheckDirectory(new FileInfo(l_oDocument.MultiVolumePath).DirectoryName);
                        LogManager.Instance().LogDebug(
                            "----------------- Trying to move thumbnail from [" +
                            GetThumbDocumentFullPath(l_oDocument.ImageName, p_lUserId) + "] to [" +
                            l_oDocument.MultiVolumePath + "]" + DateTime.Now);
                        File.Move(GetThumbDocumentFullPath(l_oDocument.ImageName, p_lUserId),
                                  l_oDocument.MultiVolumePath);
                        LogManager.Instance().LogInfo("----------------- File moved from [" +
                                                      GetThumbDocumentFullPath(l_oDocument.ImageName,
                                                                               p_lUserId) + "] to [" +
                                                      l_oDocument.MultiVolumePath + "]" + DateTime.Now);

                        //Deleting the cache
                        Treatments.DeleteAllImportCacheFiles(p_lUserId, l_oDocument.ImageName);
                    }
                    catch (IOException ex1)
                    {
                        l_oDocumentReturn = new Document(ex1.ToString(),
                                                         new Exception(ex1.ToString()))
                                                {Identifier = l_oDocument.Identifier};
                        LogManager.Instance().LogError("------------IOException in MoveImportDocument" +
                                                       l_oDocumentReturn.FullErrorMessage + " ----- " +
                                                       DateTime.Now);
                    }
                    catch (Exception ex)
                    {
                        l_oDocumentReturn = new Document(ex.ToString(),
                                                         new Exception(ex.ToString()))
                                                {Identifier = l_oDocument.Identifier};
                        LogManager.Instance().LogError("------------Exception in MoveImportDocument" +
                                                       l_oDocumentReturn.FullErrorMessage + " ----- " +
                                                       DateTime.Now);
                    }

                    l_lstReturnDocument.Add(l_oDocumentReturn);
                }

                LogManager.Instance().LogInfo(string.Empty);
                LogManager.Instance().LogInfo("---MoveImportDocument-----------------");
                LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

                return l_lstReturnDocument;
            }
        }

        /// <summary>
        ///   Moves the document with full path.
        /// </summary>
        /// <param name="p_lstDocument"> The document. </param>
        /// <param name="p_lUserId"> The user id. </param>
        /// <param name="p_oMessageRequest"> The message request. </param>
        /// <returns> </returns>
        public List<Document> MoveOrCopyDocumentWithFullPath(
            List<Document> p_lstDocument, long p_lUserId, bool isMoveAction,
            MessageRequest p_oMessageRequest)
        {
            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            lock (m_LockObject)
            {
                LogManager.ConfigFile(
                    ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
                LogManager.Instance().LogInfo(string.Empty);
                LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
                LogManager.Instance().LogInfo("---MoveDocumentWithFullPath-----p_lstDocument.Count[" +
                                              p_lstDocument.Count + "]---p_lUSerId[" + p_lUserId + "]");

                var l_lstReturnDocument = new List<Document>();

                foreach (var l_oDocument in p_lstDocument)
                {
                    var l_oDocumentReturn = new Document();
                    try
                    {
                        var l_oTreatments = new Treatments();
                        l_oDocumentReturn.Identifier = l_oDocument.Identifier;
                        l_oDocumentReturn.OriginalNameFile = l_oDocument.OriginalNameFile;

                        //**Move document to the stock path
                        Treatments.CheckDirectory(new FileInfo(l_oDocument.MultiVolumePath).DirectoryName);
                        l_oTreatments.CreateThumb(l_oDocument.ImageName, l_oDocument.MultiVolumePath);

                        LogManager.Instance().LogInfo("----------------- Thumbnail created for [" +
                                                      l_oDocument.MultiVolumePath + "]" + DateTime.Now);

                        Treatments.CheckDirectory(new FileInfo(l_oDocument.RelativePath).DirectoryName);
                        if (isMoveAction)
                            File.Move(l_oDocument.ImageName, l_oDocument.RelativePath);
                        else
                            File.Copy(l_oDocument.ImageName, l_oDocument.RelativePath);

                        LogManager.Instance().LogInfo("----------------- File copied from [" +
                                                      l_oDocument.ImageName + "] to [" +
                                                      l_oDocument.RelativePath + "]" + DateTime.Now);
                    }
                    catch (Exception ex)
                    {
                        l_oDocumentReturn = new Document(ex.Message,
                                                         new Exception(ex.Message))
                                                {Identifier = l_oDocument.Identifier};
                        LogManager.Instance().LogError(
                            "------------Exception in MoveDocumentWithFullPath" + l_oDocumentReturn.FullErrorMessage +
                            " ----- " + DateTime.Now);
                    }

                    l_lstReturnDocument.Add(l_oDocumentReturn);
                }

                LogManager.Instance().LogInfo(string.Empty);
                LogManager.Instance().LogInfo("---MoveDocumentWithFullPath-----------------");
                LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

                return l_lstReturnDocument;
            }
        }

        /// <summary>
        ///   Put a document in the temporary directory just as RioScann does
        /// </summary>
        /// <param name="p_oDocument"> The serialized document as a Byte array </param>
        /// <param name="p_sDocumentName"> Document Name </param>
        /// <param name="p_iUserId"> The user identifier </param>
        /// <returns> True if success </returns>
        public void PostDocument(byte[] p_oDocument, string p_sDocumentName, long p_iUserId)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---PostDocument-----p_sDocumentName[" + p_sDocumentName + "]");

            try
            {
                Treatments.CheckDirectory(
                    Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.InputDirectory"),
                                 p_iUserId.ToString()));

                var l_sFullPath = GetImportDocumentFullPath(p_sDocumentName, p_iUserId);
                using (Treatments l_oTreatments = new Treatments())
                {
                    Treatments.CheckDirectory(new FileInfo(l_sFullPath).DirectoryName);

                    LogManager.Instance().LogInfo("------------------ Reading file[" + l_sFullPath +
                                                  "]-----");
                    var fs = new FileStream(l_sFullPath, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
                    var bw = new BinaryWriter(fs);
                    bw.Write(p_oDocument);
                    LogManager.Instance().LogInfo("------------------ File Created [" + l_sFullPath +
                                                  "]-----");
                    bw.Close();
                    fs.Close();

                    var l_sOutputPath =
                        Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.OutputDirectory"),
                                     p_iUserId.ToString());

                    //Generating the tumbnail
                    l_oTreatments.CreateThumb(GetImportDocumentFullPath(p_sDocumentName, p_iUserId),
                                              Path.Combine(l_sOutputPath, p_sDocumentName) +
                                              Constant.ImageFileFormat.JPG.szGetDescription());

                    //Added code to delete all archive
                    //Treatments.DeleteAllImportCacheFiles(p_iUserId, p_sDocumentName);
                }
            }
            catch (Exception ex)
            {
                LogManager.Instance().LogError(ex.Message);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---PostDocument-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");
        }

        /// <summary>
        ///   Returns the value that the ocrengin find for each couple OcrArea/index
        /// </summary>
        /// <param name="p_sFileName"> Name of the file </param>
        /// <param name="p_lstOcrMaskItem"> List of all OcrMaskItem to process </param>
        /// <param name="p_lUserId"> Identifier of the user </param>
        /// <returns> All OcrMaskItem with the string found by the ocr engine </returns>
        public List<OcrMaskItem> ProcessOcr(string p_sFileName, List<OcrMaskItem> p_lstOcrMaskItem, long p_lUserId,
                                            MessageRequest p_oMessageRequest)
        {
            //Number passage of océrisation
            int OcrPass = 2;
            string sOCR = string.Empty;

            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo(String.Format(
                "---ProcessOcr-----p_sFileName[{0}]-----p_lstOcrMaskItem.Count[{1}]-----p_lUserId[{2}]",
                p_sFileName,
                p_lstOcrMaskItem.Count,
                p_lUserId));

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            try
            {
                LicenseGdPicture();
                int l_iDpi =
                    Convert.ToInt16(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.GdPicture.OCR.PDF.DPI"));
                var l_sFileNameFullPath = GetImportDocumentFullPath(p_sFileName, p_lUserId);

                int m_iImageID = -1;
                string l_oFileExtension = Path.GetExtension(p_sFileName);
                if (l_oFileExtension.ToLower().Equals(Constant.DocumentFileFormat.PDF.szGetDescription()))
                {
                    if (m_oGdPicturePDF.LoadFromFile(l_sFileNameFullPath, false) == GdPictureStatus.OK)
                    {
                        m_oGdPicturePDF.SelectPage(1);
                        m_iImageID = m_oGdPicturePDF.RenderPageToGdPictureImage(l_iDpi, true);

                        //Check for A4 paper format
                        var l_iCurrentDpi = m_oGdPictureImaging.GetWidth(m_iImageID)/8.25;
                        if (!((l_iCurrentDpi <= l_iDpi*1.10) && (l_iCurrentDpi >= l_iDpi*0.90)))
                        {
                            m_oGdPictureImaging.ResizeWidthRatio(m_iImageID, Convert.ToInt16(l_iDpi*8.25),
                                                                 InterpolationMode.Default);
                        }

                        m_oGdPicturePDF.CloseDocument();
                    }
                }
                else
                {
                    m_iImageID = m_oGdPictureImaging.CreateGdPictureImageFromFile(l_sFileNameFullPath);
                }

                foreach (var l_oOcrMaskItem in p_lstOcrMaskItem)
                {
                    //Add zone Area
                    m_oGdPictureImaging.SetROI(Convert.ToInt32(l_oOcrMaskItem.Area.X),
                                               Convert.ToInt32(l_oOcrMaskItem.Area.Y),
                                               Convert.ToInt32(l_oOcrMaskItem.Area.Width),
                                               Convert.ToInt32(l_oOcrMaskItem.Area.Height));
                    m_oGdPictureImaging.OCRTesseractReinit();
                    m_oGdPictureImaging.OCRTesseractSetPassCount(OcrPass);
                    var p_StockDictionaryGdPicture = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
                                                                  "DictionaryGdPicture");
                    sOCR = m_oGdPictureImaging.OCRTesseractDoOCR(m_iImageID,
                                                                 ConfigurationManager.AppSettings.Get(
                                                                     "Rio.WCF.Services.GdPicture.OCR.Language"),
                                                                 p_StockDictionaryGdPicture, "");

                    l_oOcrMaskItem.OcrValue = sOCR;
                    l_oOcrMaskItem.OcrValue = l_oOcrMaskItem.OcrValue.Replace("\r", "").Replace("\n", "");
                }
                //Shutdown GdPicture
                m_oGdPictureImaging.OCRTesseractClear();
                m_oGdPictureImaging.ClearGdPicture();
            }
            catch (Exception e)
            {
                LogManager.Instance().LogError(e.Message);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---ProcessOcr-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return p_lstOcrMaskItem;
        }

        /// <summary>
        ///   Returns the value that the ocrengin find for each couple OcrArea/index
        /// </summary>
        /// <param name="p_sFileName"> Name of the file </param>
        /// <param name="p_oOcrArea"> The OcrmaskArea to ocrize </param>
        /// <param name="p_lUserId"> Identifier of the user </param>
        /// <param name="p_oOcrType"> </param>
        /// <returns> The string found by the ocr engine </returns>
        /// CAUTION, NE PAS ENLEVER POUR L'INSTANT
        public string ProcessOcrArea(string p_sFileName, OcrArea p_oOcrArea, long p_lUserId, OcrType p_oOcrType,
                                     MessageRequest p_oMessageRequest)
        {
            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            var l_sReturnValue = String.Empty;

            //NetBay.Core.Log.LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            //NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
            //NetBay.Core.Log.LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            //NetBay.Core.Log.LogManager.Instance().LogInfo(String.Format(
            //    "---ProcessOcrArea-----p_sFileName[{0}]-----p_oOcrArea[{1}]-----p_lUserId[{2}]-----p_oOcrType[{3}]",
            //    p_sFileName,
            //    p_oOcrArea.Name,
            //    p_lUserId,
            //    p_oOcrType));

            //try
            //{
            //    #region Leadtools Initialisation

            //    LeadtoolsLicence();

            //    #endregion

            //    using (var l_oCodecs = new RasterCodecs())
            //    {
            //        #region Resolution settings
            //        l_oCodecs.Options.Load.XResolution = 200;
            //        l_oCodecs.Options.Load.YResolution = 200;
            //        #endregion

            //        // Start the engine using default parameters 
            //        IOcrEngine l_oOcrEngine = null;

            //        using (l_oOcrEngine = OcrEngineManager.CreateEngine(OcrEngineType.Advantage, false))
            //        {
            //            l_oOcrEngine.Startup(l_oCodecs, null, null, null);

            //            // Create a document 
            //            var l_oOcrDocumentManager = l_oOcrEngine.DocumentManager;
            //            var l_sFileNameFullPath = GetImportDocumentFullPath(p_sFileName, p_lUserId);

            //            using (var l_oOcrDocumentArea = l_oOcrDocumentManager.CreateDocument())
            //            {
            //                var l_oOcrPageArea = l_oOcrDocumentArea.Pages.AddPage(l_sFileNameFullPath, null);

            //                // Clear all the zones in the page 
            //                l_oOcrPageArea.Zones.Clear();

            //                // Add our field zone 
            //                var l_oOcrZoneArea = new OcrZone
            //                {
            //                    RecognitionModule = OcrZoneRecognitionModule.Auto,
            //                    Bounds = new LogicalRectangle(p_oOcrArea.X,
            //                                            p_oOcrArea.Y,
            //                                            p_oOcrArea.Width,
            //                                            p_oOcrArea.Height,
            //                                            LogicalUnit.Pixel)
            //                };

            //                if (p_oOcrType != OcrType.Auto)
            //                {
            //                    switch (p_oOcrType)
            //                    {
            //                        case OcrType.Asian:
            //                            l_oOcrZoneArea.FillMethod = OcrZoneFillMethod.Asian;
            //                            break;
            //                        case OcrType.HandPrinted:
            //                            l_oOcrZoneArea.FillMethod = OcrZoneFillMethod.Icr;
            //                            break;
            //                        case OcrType.MagneticInk:
            //                            l_oOcrZoneArea.FillMethod = OcrZoneFillMethod.Micr;
            //                            break;
            //                        case OcrType.MachinePrinted:
            //                            l_oOcrZoneArea.FillMethod = OcrZoneFillMethod.OmniFont;
            //                            break;
            //                    }
            //                }
            //                else
            //                    l_oOcrZoneArea.FillMethod = OcrZoneFillMethod.Default;

            //                l_oOcrPageArea.Zones.Add(l_oOcrZoneArea);

            //                l_sReturnValue = l_oOcrPageArea.RecognizeText(null);
            //            }
            //        }

            //        l_oOcrEngine.Shutdown();
            //    }
            //}
            //catch (Exception e)
            //{
            //    NetBay.Core.Log.LogManager.Instance().LogError(e.Message);
            //}


            //NetBay.Core.Log.LogManager.Instance().LogInfo(string.Empty);
            //NetBay.Core.Log.LogManager.Instance().LogInfo("---ProcessOcrArea-----------------");
            //NetBay.Core.Log.LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return l_sReturnValue.Replace("\r", "").Replace("\n", "");
        }

        /// <summary>
        ///   Put a document in the temporary directory just as RioScann does
        /// </summary>
        /// <param name="p_oDocumentSegment"> The serialized document as a Byte array </param>
        /// <param name="p_sDocumentName"> Document Name </param>
        /// <param name="p_iUserId"> The user identifier </param>
        /// <param name="p_oSegmentGuid"> </param>
        /// <param name="p_iSegmentOrder"> </param>
        /// <param name="p_bLastSegment"> </param>
        /// <returns> True if success </returns>
        public ImageRio PostDocumentWithSegment(byte[] p_oDocumentSegment, string p_sDocumentName, long p_iUserId,
                                                Guid p_oSegmentGuid, int p_iSegmentOrder, Boolean p_bLastSegment)
        {
            return BasePostDocumentWithSegment(p_oDocumentSegment, p_sDocumentName, p_iUserId, p_oSegmentGuid,
                                               p_iSegmentOrder, p_bLastSegment);
        }

        /// <summary>
        ///   Put a document in the temporary directory just as RioScann does without creating thumbnail
        /// </summary>
        /// <param name="p_oDocumentSegment"> The serialized document as a Byte array </param>
        /// <param name="p_sDocumentName"> Document Name </param>
        /// <param name="p_iUserId"> The user identifier </param>
        /// <param name="p_oSegmentGuid"> </param>
        /// <param name="p_iSegmentOrder"> </param>
        /// <param name="p_bLastSegment"> </param>
        /// <returns> True if success </returns>
        public ImageRio PostDocumentWithSegmentNoThumbnail(byte[] p_oDocumentSegment, string p_sDocumentName,
                                                           long p_iUserId, Guid p_oSegmentGuid, int p_iSegmentOrder,
                                                           Boolean p_bLastSegment)
        {
            return BasePostDocumentWithSegment(p_oDocumentSegment, p_sDocumentName, p_iUserId, p_oSegmentGuid,
                                               p_iSegmentOrder, p_bLastSegment, false);
        }

        /// <summary>
        ///   Put a document in the temporary directory just as RioScann does --> with directory between IdUser and filname
        /// </summary>
        /// <param name="p_oDocumentSegment"> The serialized document as a Byte array </param>
        /// <param name="p_sDocumentName"> Document Name </param>
        /// <param name="p_iUserId"> The user identifier </param>
        /// <param name="p_oSegmentGuid"> </param>
        /// <param name="p_iSegmentOrder"> </param>
        /// <param name="p_bLastSegment"> </param>
        /// <param name="p_sDirectory"> The Directory between Ididentifier and the Document Name </param>
        /// <returns> True if success </returns>
        public ImageRio PostDocumentWithSegmentAndDirectory(byte[] p_oDocumentSegment, string p_sDocumentName,
                                                            long p_iUserId, Guid p_oSegmentGuid, int p_iSegmentOrder,
                                                            Boolean p_bLastSegment, string p_sDirectory)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo(
                "---PostDocumentWithSegmentAndDirectory-----p_sDocumentName[" + p_sDocumentName + "] p_iUserId[" +
                p_iUserId + "]  p_oSegmentGuid[" + p_oSegmentGuid + "]  p_iSegmentOrder[" + p_iSegmentOrder +
                "]  p_bLastSegment[" + p_bLastSegment + "] p_sDirectory[" + p_sDirectory + "]");

            var l_oImageRio = new ImageRio();

            try
            {
                //Checking that the directory exists
                var l_sTemporaryDirectory = ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory");
                var l_otempDir = Path.Combine(l_sTemporaryDirectory, p_oSegmentGuid.ToString("N"));
                Treatments.CheckDirectory(l_otempDir);

                var l_sFileName = Path.Combine(l_otempDir,
                                               p_sDocumentName + "_" + p_oSegmentGuid.ToString("N") + "." +
                                               p_iSegmentOrder.ToString("000000000000000"));
                LogManager.Instance().LogInfo("---------- Writing file-----[" + l_sFileName + "]");
                using (Stream l_oStream = File.Create(l_sFileName))
                {
                    l_oStream.Write(p_oDocumentSegment, 0, p_oDocumentSegment.Length);
                }

                var l_oDi = new DirectoryInfo(l_otempDir);
                var l_oRgFiles = l_oDi.GetFiles("*.*");
                var l_oOrderedFiles = l_oRgFiles.OrderBy(f => f.Name);
                if (p_bLastSegment)
                {
                    LogManager.Instance().LogInfo("---------- Rebuilding the file");

                    var l_sDocumentFileFullPath = GetImportDocumentFullPath(p_sDocumentName, p_iUserId, p_sDirectory);
                    Treatments.CheckDirectory(new FileInfo(l_sDocumentFileFullPath).DirectoryName);
                    var l_oOutputFS = File.Create(l_sDocumentFileFullPath);
                    JoinFiles(l_otempDir, l_oOutputFS);

                    foreach (var l_oFileInfo in l_oOrderedFiles)
                    {
                        LogManager.Instance().LogInfo("----------  Deleting file [" +
                                                      l_oFileInfo.FullName + "]");
                        File.Delete(l_oFileInfo.FullName);
                    }

                    var l_oTreatments = new Treatments
                                            {
                                                FillMetadataInImageRio = true,
                                                ImageRioToFillMetadata = l_oImageRio
                                            };

                    var l_bFileTransfered = false;
                    while (!l_bFileTransfered)
                    {
                        try
                        {
                            using (
                                new FileStream(l_sDocumentFileFullPath, FileMode.Open, FileAccess.Read,
                                               FileShare.ReadWrite))
                            {
                                l_bFileTransfered = true;
                            }
                        }
                            // Catch to wait until file is completely transfered
                        catch
                        {
                        }
                    }

                    var l_sThumbnailOutputPath =
                        Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.OutputDirectory"),
                                     p_iUserId.ToString(), p_sDirectory);
                    var l_sThumbFileNamefullPath = GetThumbDocumentFullPath(p_sDocumentName, p_iUserId, p_sDirectory);

                    Treatments.CheckDirectory(new FileInfo(l_sThumbnailOutputPath).DirectoryName);
                    l_oTreatments.CreateThumb(GetImportDocumentFullPath(p_sDocumentName, p_iUserId, p_sDirectory),
                                              l_sThumbFileNamefullPath);

                    //Added code to delete all archive
                    //Treatments.DeleteAllImportCacheFiles(p_iUserId, p_sDocumentName);


                    var l_oFileStream = new FileStream(l_sThumbFileNamefullPath, FileMode.Open, FileAccess.Read,
                                                       FileShare.ReadWrite);
                    var binary = StreamtoByteArray(l_oFileStream);
                    l_oFileStream.Close();
                    l_oFileStream.Dispose();

                    l_oImageRio.Img = binary;
                    l_oImageRio.Name = Path.GetFileName(l_sThumbFileNamefullPath);

                    FileInfo documentFileInfo = new FileInfo(l_sDocumentFileFullPath);

                    l_oImageRio.NumberPages = GetNumberOfPageInDocument(documentFileInfo);

                    binary = null;
                    LogManager.Instance().LogInfo("---------- Deleting directory [" + l_otempDir + "]");

                    Treatments.DeleteDirectory(l_otempDir);
                    Treatments.DeleteDirectory(
                        Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory"),
                                     p_iUserId + "\\" + p_sDirectory + "\\" + p_sDocumentName));
                }
            }
            catch (Exception ex)
            {
                l_oImageRio.IsValid = false;
                l_oImageRio.ErrorMessage =
                    "------------- EXCEPTION IN WCF PostDocumentWithSegmentAndDirectory EXCEPTION[" + DateTime.Now + "]" +
                    ex.Message;
                LogManager.Instance().LogError(
                    "------------- EXCEPTION IN WCF PostDocumentWithSegmentAndDirectory [" + DateTime.Now +
                    "]  Exception " + ex.Message);
            }
            finally
            {
                LogManager.Instance().LogInfo(string.Empty);
                LogManager.Instance().LogInfo("---PostDocumentWithSegmentAndDirectory-----------------");
                LogManager.Instance().LogInfo("END OF WCF SERVICE CALL ---------------------");
            }

            return l_oImageRio;
        }

        /// <summary>
        ///   Put a document in the temporary directory just as RioScann does --&gt; with directory between IdUser and filname
        /// </summary>
        /// <param name="p_oDocumentSegment"> The serialized document as a Byte array </param>
        /// <param name="p_sDocumentNameFullPath"> Document Name and FullPath </param>
        /// <param name="p_sStockPath"> The P_S stock path. </param>
        /// <param name="p_oSegmentGuid"> The p_o segment GUID. </param>
        /// <param name="p_iSegmentOrder"> The p_i segment order. </param>
        /// <param name="p_bLastSegment"> if set to <c>true</c> [P_B last segment]. </param>
        /// <param name="p_bMustOverWrite"> if set to <c>true</c> [P_B must over write]. </param>
        /// <returns> True if success </returns>
        public ImageRio PostDocumentWithSegmentAndDirectoryMove(byte[] p_oDocumentSegment,
                                                                string p_sDocumentNameFullPath, string p_sStockPath,
                                                                Guid p_oSegmentGuid, int p_iSegmentOrder,
                                                                Boolean p_bLastSegment, Boolean p_bMustOverWrite)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo(
                "---PostDocumentWithSegmentAndDirectoryMove-----p_sDocumentNameFullPath[" + p_sDocumentNameFullPath +
                "] p_oSegmentGuid[" + p_oSegmentGuid + "] p_sStockPath[" + p_sStockPath + "] p_iSegmentOrder[" +
                p_iSegmentOrder + "]  p_bLastSegment[" + p_bLastSegment + "]");
            var l_oImageRio = new ImageRio();

            //Checking and creting the temporary directory
            string l_otempDir = Path.Combine(
                ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory"),
                p_oSegmentGuid.ToString("N"));
            Treatments.CheckDirectory(l_otempDir);

            try
            {
                //Create a temporary filename
                string l_sDocumentNameCut = Path.GetRandomFileName() + Path.GetExtension(p_sDocumentNameFullPath);

                //Construction Directory or to find the thumbnail
                string l_StockThumbNail = Path.Combine(p_sStockPath,
                                                       ConfigurationManager.AppSettings.Get("Rio.WCF.Services.ThumbNail"));
                string l_sFileName = Path.Combine(l_otempDir,
                                                  p_oSegmentGuid.ToString("N") + "." +
                                                  p_iSegmentOrder.ToString("000000000000000"));

                LogManager.Instance().LogInfo("---------- Writing file-----[" + l_sFileName + "]");
                using (Stream l_oStream = File.Create(l_sFileName))
                {
                    l_oStream.Write(p_oDocumentSegment, 0, p_oDocumentSegment.Length);
                }

                var l_oDi = new DirectoryInfo(l_otempDir);
                var l_oRgFiles = l_oDi.GetFiles("*.*");
                var l_oOrderedFiles = l_oRgFiles.OrderBy(f => f.Name);
                if (p_bLastSegment)
                {
                    LogManager.Instance().LogInfo("---------- Rebuilding the file");
                    //Create folder temp
                    string l_sPathSource =
                        Path.Combine(
                            ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory"),
                            l_sDocumentNameCut);

                    //var l_sDocumentFileFullPath = l_sPathSource;
                    Treatments.CheckDirectory(new FileInfo(l_sPathSource).DirectoryName);

                    var l_oOutputFS = File.Create(l_sPathSource);
                    JoinFiles(l_otempDir, l_oOutputFS);

                    foreach (var l_oFileInfo in l_oOrderedFiles)
                    {
                        LogManager.Instance().LogInfo("----------  Deleting file [" +
                                                      l_oFileInfo.FullName + "]");
                        File.Delete(l_oFileInfo.FullName);
                    }

                    var l_oTreatments = new Treatments
                                            {
                                                FillMetadataInImageRio = true,
                                                ImageRioToFillMetadata = l_oImageRio
                                            };

                    var l_bFileTransfered = false;
                    while (!l_bFileTransfered)
                    {
                        try
                        {
                            using (new FileStream(l_sPathSource, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                            {
                                l_bFileTransfered = true;
                            }
                        }
                            // Catch to wait until file is completely transfered
                        catch
                        {
                        }
                    }

                    //Document path
                    string l_sPathDestination = Path.Combine(p_sStockPath,
                                                             Path.GetDirectoryName(p_sDocumentNameFullPath));
                    string l_sPathdocumentDestination = Path.Combine(l_sPathDestination,
                                                                     Path.GetFileName(p_sDocumentNameFullPath));

                    //Thumbnail path
                    string l_sThumbnailOutputPath = Path.Combine(l_StockThumbNail,
                                                                 Path.GetDirectoryName(p_sDocumentNameFullPath));
                    string l_sThumbNailOutFullPath = Path.Combine(l_sThumbnailOutputPath,
                                                                  Path.GetFileNameWithoutExtension(
                                                                      p_sDocumentNameFullPath) +
                                                                  Constant.ImageFileFormat.JPG.szGetDescription());


                    //If p_bMustOverWrite =true, we must to delete the existing file and put the new, similar to the vignette
                    if (p_bMustOverWrite)
                    {
                        if (File.Exists(l_sPathdocumentDestination))
                        {
                            File.Delete(l_sPathdocumentDestination);
                        }
                    }

                    //Create the document where is stocked the new document
                    Treatments.CheckDirectory(l_sPathDestination);

                    //Construction of the path and filename of the thumbnail
                    l_oTreatments.CreateThumb(l_sPathSource, l_sThumbNailOutFullPath);

                    Treatments.DeleteAllCacheFiles(new FileInfo(l_sPathdocumentDestination).Name);

                    //Move document
                    if (!File.Exists(l_sPathdocumentDestination))
                        File.Move(l_sPathSource, l_sPathdocumentDestination);

                    //Deleted the folder temp
                    Treatments.DeleteFile(l_sPathSource);
                    Treatments.DeleteDirectory(l_otempDir);
                }
            }
            catch (Exception ex)
            {
                l_oImageRio.IsValid = false;
                l_oImageRio.ErrorMessage =
                    "------------- EXCEPTION IN WCF PostDocumentWithSegmentAndDirectoryMove EXCEPTION[" + DateTime.Now +
                    "]" + ex.Message;
                LogManager.Instance().LogError(
                    "------------- EXCEPTION IN WCF PostDocumentWithSegmentAndDirectoryMove [" + DateTime.Now +
                    "]  Exception " + ex.Message);
            }
            finally
            {
                LogManager.Instance().LogInfo(string.Empty);
                LogManager.Instance().LogInfo(
                    "---PostDocumentWithSegmentAndDirectoryMove-----------------");
                LogManager.Instance().LogInfo("END OF WCF SERVICE CALL ---------------------");
            }

            return l_oImageRio;
        }

        /// <summary>
        ///   Allow to rotate an image
        /// </summary>
        /// <param name="p_oImage"> Image to rotate </param>
        /// <param name="p_fAngle"> Angle of rotation </param>
        /// <param name="p_sExtension"> The P_S extension. </param>
        /// <param name="p_oMessageRequest"> The p_o message request. </param>
        /// <returns> A ReturnByte object containing the byte[] and information about the call of the service </returns>
        public ReturnByte RotateImage(byte[] p_oImage, RotateFlipType p_fAngle, string p_sExtension,
                                      MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---RotateImage-----");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            byte[] l_oBitmapData = null;
            var l_oReturnByte = new ReturnByte(l_oBitmapData);

            int imageID = 0;
            try
            {
                int l_oBytesRead = 0;
                GdPictureStatus status;

                imageID = m_oGdPictureImaging.CreateGdPictureImageFromByteArray(p_oImage);

                status = m_oGdPictureImaging.Rotate(imageID, p_fAngle);
                LogManager.Instance().LogDebug("Rotate status:" + status.ToString());

                status = m_oGdPictureImaging.SaveAsByteArray(imageID, ref l_oBitmapData, ref l_oBytesRead,
                                                             DocumentFormat.DocumentFormatJPEG, 0);
                LogManager.Instance().LogDebug("SaveAsByteArray status: " + status.ToString());

                status = m_oGdPictureImaging.ReleaseGdPictureImage(imageID);
                LogManager.Instance().LogDebug("ReleaseGdPictureImage status:" + status.ToString());

                l_oReturnByte.Value = l_oBitmapData;
            }
            catch (Exception ex)
            {
                l_oReturnByte =
                    new ReturnByte(
                        "------------- EXCEPTION IN WCF RotateImage EXCEPTION: EXCEPTION[" + DateTime.Now + "]",
                        new Exception(ex.ToString()));
                LogManager.Instance().LogError(l_oReturnByte.FullErrorMessage);
            }
            finally
            {
                if (imageID > 0)
                    m_oGdPictureImaging.ReleaseGdPictureImage(imageID);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---RotateImage-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return l_oReturnByte;
        }

        /// <summary>
        ///   Allow to save images with a specific rotation
        /// </summary>
        /// <param name="p_lstImagesToRotateAndSave"> List of all images to rotate with their specific rotations </param>
        /// <param name="p_lUserId"> User Identifier </param>
        /// <param name="p_oMessageRequest"> The p_o message request. </param>
        /// <returns> A ReturnBoolean containing informations about the rotation </returns>
        public ReturnObject SaveImportRotatedImages(
            Dictionary<string, Dictionary<int, RotateFlipType>> p_lstImagesToRotateAndSave, long p_lUserId,
            MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo(
                "---SaveImportRotatedImages----- p_lstImagesToRotateAndSave[" + p_lstImagesToRotateAndSave.Count +
                "] -- p_iUserId [" + p_lUserId + "]");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            ReturnObject l_oReturnObject;
            var p_lstImagesToRotateAndSaveTemp = new Dictionary<string, Dictionary<int, RotateFlipType>>();

            try
            {
                foreach (var l_sItem in p_lstImagesToRotateAndSave.Keys)
                {
                    p_lstImagesToRotateAndSaveTemp.Add(GetImportDocumentFullPath(l_sItem, p_lUserId),
                                                       p_lstImagesToRotateAndSave[l_sItem]);
                }
                l_oReturnObject = SaveRotatedImagesWithFullPath(p_lstImagesToRotateAndSaveTemp, p_oMessageRequest,
                                                                p_lUserId);
            }
            catch (Exception ex)
            {
                l_oReturnObject =
                    new ReturnObject(
                        "------------- EXCEPTION IN WCF SaveImportRotatedImages EXCEPTION[" + DateTime.Now + "]",
                        new Exception(ex.Message));
                LogManager.Instance().LogError(l_oReturnObject.FullErrorMessage);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---SaveImportRotatedImages-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return l_oReturnObject;
        }

        /// <summary>
        ///   Allow to save images with a specific rotation
        /// </summary>
        /// <param name="p_lstImagesToRotateAndSave"> List of all images to rotate with their specific rotations </param>
        /// <param name="p_lUserId"> User Identifier </param>
        /// <param name="p_sDirectoryName"> Name of the P_S directory. </param>
        /// <param name="p_oMessageRequest"> The p_o message request. </param>
        /// <returns> A ReturnBoolean containing informations about the rotation </returns>
        public ReturnObject SaveImportRotatedImagesWithDirectory(
            Dictionary<string, Dictionary<int, RotateFlipType>> p_lstImagesToRotateAndSave, long p_lUserId,
            string p_sDirectoryName, MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo(
                "---SaveImportRotatedImagesWithDirectory----- p_lstImagesToRotateAndSave[" +
                p_lstImagesToRotateAndSave.Count + "] -- p_iUserId [" + p_lUserId + "]");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            ReturnObject l_oReturnObject;
            var p_lstImagesToRotateAndSaveTemp = new Dictionary<string, Dictionary<int, RotateFlipType>>();

            try
            {
                foreach (var l_sItem in p_lstImagesToRotateAndSave.Keys)
                {
                    p_lstImagesToRotateAndSaveTemp.Add(GetImportDocumentFullPath(l_sItem, p_lUserId),
                                                       p_lstImagesToRotateAndSave[l_sItem]);
                }
                l_oReturnObject = SaveRotatedImagesWithFullPathAndDirectory(p_lstImagesToRotateAndSaveTemp,
                                                                            p_oMessageRequest, p_lUserId,
                                                                            p_sDirectoryName);
            }
            catch (Exception ex)
            {
                l_oReturnObject =
                    new ReturnObject(
                        "------------- EXCEPTION IN WCF SaveImportRotatedImagesWithDirectory EXCEPTION[" + DateTime.Now +
                        "]", new Exception(ex.Message));
                LogManager.Instance().LogError(l_oReturnObject.FullErrorMessage);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---SaveImportRotatedImagesWithDirectory-----------------");
            LogManager.Instance().LogInfo("END OF WCF SERVICE CALL ---------------------");

            return l_oReturnObject;
        }

        /// <summary>
        ///   Check if a refresh file exists
        /// </summary>
        /// <param name="p_sGuidToString"> A guid ToString("N") </param>
        /// <param name="p_oMessageRequest"> </param>
        public ReturnBoolean RefreshFileExists(string p_sGuidToString, MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---RefreshFileExists----- p_sGuidToString[" + p_sGuidToString +
                                          "]");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            var l_oReturnBoolean = new ReturnBoolean(false);

            try
            {
                var l_sTemporaryDirectoryDirectory =
                    ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory");
                Treatments.CheckDirectory(l_sTemporaryDirectoryDirectory);
                var l_sFullPathOfRefreshFile = Path.Combine(l_sTemporaryDirectoryDirectory,
                                                            p_sGuidToString
                    );
                LogManager.Instance().LogInfo("-------RefreshFileExists----- Checking if the file [" +
                                              l_sTemporaryDirectoryDirectory + "] exists");

                if (File.Exists(l_sFullPathOfRefreshFile))
                    l_oReturnBoolean.Value = true;
            }
            catch (Exception ex)
            {
                LogManager.Instance().LogError(ex.Message);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---RefreshFileExists-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");
            return l_oReturnBoolean;
        }

        /// <summary>
        ///   Allow to save images with a specific rotation
        /// </summary>
        /// <param name="p_lstImagesToRotateAndSave"> Document Name </param>
        /// <param name="p_oMessageRequest"> The p_o message request. </param>
        /// <param name="p_lUserId"> User identifier </param>
        /// <returns> A ReturnBoolean containing informations about the rotation </returns>
        public ReturnObject SaveRotatedImagesWithFullPath(
            Dictionary<string, Dictionary<int, RotateFlipType>> p_lstImagesToRotateAndSave,
            MessageRequest p_oMessageRequest, long p_lUserId = 0)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo(
                "---SaveRotatedImagesWithFullPath----- p_lstImagesToRotateAndSave[" + p_lstImagesToRotateAndSave.Count +
                "]");

            ReturnObject l_oReturnObject = SaveRotatedImagesWithFullPathAndDirectory(p_lstImagesToRotateAndSave,
                                                                                     p_oMessageRequest, p_lUserId, null);

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---SaveRotatedImagesWithFullPath-----------------");
            LogManager.Instance().LogInfo("END OF WCF SERVICE CALL ---------------------");

            return l_oReturnObject;
        }

        /// <summary>
        ///   Allow to save images with a specific rotation
        /// </summary>
        /// <param name="p_lstImagesToRotateAndSave"> Document Name </param>
        /// <param name="p_oMessageRequest"> The p_o message request. </param>
        /// <param name="p_lUserId"> User identifier </param>
        /// <param name="p_sDirectoryName"> Name of the P_S directory. </param>
        /// <returns> A ReturnBoolean containing informations about the rotation </returns>
        public ReturnObject SaveRotatedImagesWithFullPathAndDirectory(
            Dictionary<string, Dictionary<int, RotateFlipType>> p_lstImagesToRotateAndSave,
            MessageRequest p_oMessageRequest, long p_lUserId = 0, string p_sDirectoryName = null)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo(
                "---SaveRotatedImagesWithFullPathAndDirectory----- p_lstImagesToRotateAndSave[" +
                p_lstImagesToRotateAndSave.Count + "]");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            // Initialization
            var l_oReturnObject = new ReturnObject();

            try
            {
                foreach (var l_sItem in p_lstImagesToRotateAndSave.Keys)
                {
                    string l_sCurrentOriginalFile;
                    string l_sCurrentThumbFile;
                    bool l_bImportMode;

                    // # This is the first to distinguish whether one is in the import screen or not.
                    //and then after the stock # is the name of the thumbnail.
                    if (l_sItem.IndexOf("#") > 1)
                    {
                        l_bImportMode = false;
                        l_sCurrentOriginalFile = l_sItem.Substring(0, l_sItem.IndexOf("#"));
                        l_sCurrentThumbFile = l_sItem.Substring(l_sItem.IndexOf("#") + 1,
                                                                l_sItem.Length - l_sItem.IndexOf("#") - 1);
                    }
                    else
                    {
                        l_bImportMode = true;
                        l_sCurrentOriginalFile = l_sItem;
                        l_sCurrentThumbFile = GetThumbDocumentFullPath(new FileInfo(l_sCurrentOriginalFile).Name,
                                                                       p_lUserId, p_sDirectoryName);
                    }

                    // It retrieves the list of rotations for this item
                    Dictionary<int, RotateFlipType> l_lstRotation = p_lstImagesToRotateAndSave[l_sItem];

                    if (
                        Path.GetExtension(l_sCurrentOriginalFile).ToLower().Equals(
                            Constant.DocumentFileFormat.PDF.szGetDescription()))
                    {
                        #region Rotation PDF

                        var l_sOutputFileNamefullPath =
                            Path.Combine(
                                ConfigurationManager.AppSettings.Get("Rio.WCF.Services.TemporaryDirectory"),
                                Guid.NewGuid().ToString("N") + Constant.DocumentFileFormat.PDF.szGetDescription());

                        var reader = new PdfReader(l_sCurrentOriginalFile);
                        int l_iRot;
                        var l_iAngle = 0;
                        PdfDictionary l_oPageDict;
                        foreach (var l_iPage in l_lstRotation.Keys)
                        {
                            l_iRot = reader.GetPageRotation(l_iPage + 1);
                            l_oPageDict = reader.GetPageN(l_iPage + 1);

                            if (l_lstRotation[l_iPage] == RotateFlipType.Rotate90FlipNone)
                            {
                                l_iAngle = 90;
                            }
                            if (l_lstRotation[l_iPage] == RotateFlipType.Rotate180FlipNone)
                            {
                                l_iAngle = 180;
                            }
                            if (l_lstRotation[l_iPage] == RotateFlipType.Rotate270FlipNone)
                            {
                                l_iAngle = 270;
                            }
                            if (l_lstRotation[l_iPage] == RotateFlipType.RotateNoneFlipNone)
                            {
                                l_iAngle = 0;
                            }

                            l_oPageDict.Put(PdfName.ROTATE, new PdfNumber((l_iRot + l_iAngle)));
                        }
                        var l_oStamper = new PdfStamper(reader,
                                                        new FileStream(l_sOutputFileNamefullPath, FileMode.CreateNew,
                                                                       FileAccess.ReadWrite, FileShare.ReadWrite));
                        l_oStamper.Close();

                        //Deleting the original file
                        File.Delete(l_sCurrentOriginalFile);
                        //Replacing the original file
                        File.Move(l_sOutputFileNamefullPath, l_sCurrentOriginalFile);

                        var l_oTreatments = new Treatments();
                        l_oTreatments.CreateThumb(l_sCurrentOriginalFile, l_sCurrentThumbFile);

                        Treatments.DeleteAllImportCacheFiles(p_lUserId, new FileInfo(l_sCurrentOriginalFile).Name);

                        #endregion
                    }
                    else
                    {
                        // The document contains more than one page.
                        if (l_lstRotation.Count > 1)
                        {
                            #region Multi Pages document

                            int m_iImageID = 0;
                            var l_oCurrentFileInfo = new FileInfo(l_sCurrentOriginalFile);

                            try
                            {
                                LogManager.Instance().LogInfo(
                                    "-------SaveRotatedImagesWithFullPathAndDirectory----- Starting a multi pages document. [" +
                                    l_sCurrentOriginalFile + "]");

                                LogManager.Instance().LogInfo(
                                    "-------SaveRotatedImagesWithFullPathAndDirectory----- new FileInfo(" +
                                    l_sCurrentOriginalFile + ")");

                                //Open file
                                m_iImageID = m_oGdPictureImaging.TiffCreateMultiPageFromFile(l_oCurrentFileInfo.FullName);
                                TiffCompression comp = m_oGdPictureImaging.GetTiffCompression(m_iImageID);
                                m_oGdPictureImaging.TiffOpenMultiPageForWrite(true);

                                foreach (var l_iPage in l_lstRotation.Keys)
                                {
                                    m_oGdPictureImaging.TiffSelectPage(m_iImageID, l_iPage + 1);
                                    m_oGdPictureImaging.Rotate(m_iImageID, l_lstRotation[l_iPage]);

                                    LogManager.Instance().LogInfo(
                                        "-------SaveRotatedImagesWithFullPathAndDirectory----- page[" + l_iPage + "]");
                                }

                                // Close and save file
                                m_oGdPictureImaging.TiffCloseMultiPageFile(m_iImageID);
                                m_oGdPictureImaging.TiffSaveMultiPageToFile(m_iImageID, l_oCurrentFileInfo.FullName,
                                                                            comp);
                                m_oGdPictureImaging.ReleaseGdPictureImage(m_iImageID);

                                //Generating the thumbnail
                                using (var l_oTreatments = new Treatments())
                                {
                                    if (l_oCurrentFileInfo.
                                            Directory != null)
                                        l_oTreatments.CreateThumb(l_oCurrentFileInfo.FullName,
                                                                  l_bImportMode
                                                                      ? GetThumbDocumentFullPath(
                                                                          l_oCurrentFileInfo.Name,
                                                                          long.Parse(
                                                                              l_oCurrentFileInfo.
                                                                                  Directory.
                                                                                  Name))
                                                                      : l_sCurrentThumbFile);
                                }

                                //We delete the cache
                                if (l_bImportMode)
                                    Treatments.DeleteAllImportCacheFiles(p_lUserId, l_oCurrentFileInfo.Name);
                                else
                                    Treatments.DeleteAllCacheFiles(l_oCurrentFileInfo.Name);
                            }
                            catch (Exception ex)
                            {
                                LogManager.Instance().LogErrorFormat(
                                    "Processing rotation on the image name:{0} failed with error:{1}",
                                    l_oCurrentFileInfo.FullName, ex.ToString());
                            }
                            finally
                            {
                                //Release gdpicture image reference
                                if (m_iImageID > 0)
                                    m_oGdPictureImaging.ReleaseGdPictureImage(m_iImageID);
                            }

                            #endregion
                        }
                        else
                        {
                            #region One Page document

                            LogManager.Instance().LogInfo(
                                "-------SaveRotatedImagesWithFullPathAndDirectory----- Starting a single page document. [" +
                                l_sCurrentOriginalFile + "]");

                            //Getting source file informations
                            var l_oCurrentFileInfo = new FileInfo(l_sCurrentOriginalFile);
                            LogManager.Instance().LogInfo("---------Processing File -----[" +
                                                          l_oCurrentFileInfo.FullName + "]");

                            //Create gdpicture image ref
                            int m_iImageID =
                                m_oGdPictureImaging.CreateGdPictureImageFromFile(l_oCurrentFileInfo.FullName);

                            try
                            {
                                if (
                                    l_oCurrentFileInfo.Extension.ToLower().Equals(
                                        Constant.ImageFileFormat.JPEG.szGetDescription()) ||
                                    l_oCurrentFileInfo.Extension.ToLower().Equals(
                                        Constant.ImageFileFormat.JPG.szGetDescription()))
                                {
                                    //JPEG
                                    m_oGdPictureImaging.Rotate(m_iImageID, l_lstRotation[0]);
                                    m_oGdPictureImaging.SaveAsJPEG(m_iImageID, l_oCurrentFileInfo.FullName);
                                }
                                else if (
                                    l_oCurrentFileInfo.Extension.ToLower().Equals(
                                        Constant.ImageFileFormat.BMP.szGetDescription()))
                                {
                                    //BMP
                                    m_oGdPictureImaging.Rotate(m_iImageID, l_lstRotation[0]);
                                    m_oGdPictureImaging.SaveAsBMP(m_iImageID, l_oCurrentFileInfo.FullName);
                                }
                                else if (
                                    l_oCurrentFileInfo.Extension.ToLower().Equals(
                                        Constant.ImageFileFormat.PNG.szGetDescription()))
                                {
                                    //JPEG
                                    m_oGdPictureImaging.Rotate(m_iImageID, l_lstRotation[0]);
                                    m_oGdPictureImaging.SaveAsPNG(m_iImageID, l_oCurrentFileInfo.FullName);
                                }
                                else if (
                                    l_oCurrentFileInfo.Extension.ToLower().Equals(
                                        Constant.ImageFileFormat.TIF.szGetDescription()) ||
                                    l_oCurrentFileInfo.Extension.ToLower().Equals(
                                        Constant.ImageFileFormat.TIFF.szGetDescription()))
                                {
                                    //TIFF: First we need to get compression to preserv it, then we set rights before rotate image
                                    TiffCompression comp = m_oGdPictureImaging.GetTiffCompression(m_iImageID);
                                    m_oGdPictureImaging.Rotate(m_iImageID, l_lstRotation[0]);
                                    m_oGdPictureImaging.SaveAsTIFF(m_iImageID, l_oCurrentFileInfo.FullName, comp);
                                }
                                else if (
                                    l_oCurrentFileInfo.Extension.ToLower().Equals(
                                        Constant.ImageFileFormat.GIF.szGetDescription()))
                                {
                                    //GIF
                                    throw new NotSupportedException("Rotation on GIF image is not supported!");
                                }
                                else
                                {
                                    l_oReturnObject =
                                        new ReturnBoolean(
                                            " Extension [" + l_oCurrentFileInfo.Extension.ToLower() +
                                            "] not supported by the rotation WCF services.", null);
                                    LogManager.Instance().LogInfo(l_oReturnObject.FullErrorMessage);
                                }


                                //We delete the cache
                                if (l_bImportMode)
                                    Treatments.DeleteAllImportCacheFiles(p_lUserId, l_oCurrentFileInfo.Name);
                                else
                                    Treatments.DeleteAllCacheFiles(l_oCurrentFileInfo.Name);

                                //Create new thumbnail
                                using (var l_oTreatments = new Treatments())
                                {
                                    if (l_oCurrentFileInfo.
                                            Directory != null)
                                        l_oTreatments.CreateThumb(l_oCurrentFileInfo.FullName,
                                                                  l_bImportMode
                                                                      ? GetThumbDocumentFullPath(
                                                                          l_oCurrentFileInfo.Name,
                                                                          long.Parse(
                                                                              l_oCurrentFileInfo.
                                                                                  Directory.
                                                                                  Name))
                                                                      : l_sCurrentThumbFile);
                                }
                            }
                            catch (Exception ex)
                            {
                                LogManager.Instance().LogErrorFormat(
                                    "Processing rotation on the image name:{0} failed with error:{1}",
                                    l_oCurrentFileInfo.FullName, ex.ToString());
                            }
                            finally
                            {
                                //Release gdpicture image reference
                                if (m_iImageID > 0)
                                    m_oGdPictureImaging.ReleaseGdPictureImage(m_iImageID);
                            }

                            #endregion
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                l_oReturnObject =
                    new ReturnBoolean(
                        "------------- EXCEPTION IN WCF SaveRotatedImagesWithFullPathAndDirectory EXCEPTION[" +
                        DateTime.Now + "]", new Exception(ex.ToString()));
                LogManager.Instance().LogError(l_oReturnObject.FullErrorMessage);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo(
                "---SaveRotatedImagesWithFullPathAndDirectory-----------------");
            LogManager.Instance().LogInfo("END OF WCF SERVICE CALL ---------------------");

            return l_oReturnObject;
        }


        /// <summary>
        ///   Explode file PDF
        /// </summary>
        /// <param name="p_sFileSource"> The P_S file source. </param>
        /// <param name="p_lUserId"> The P_L user id. </param>
        /// <param name="p_oMessageRequest"> The p_o message request. </param>
        /// <returns> </returns>
        public ReturnString ExplodePdf(string p_sFileSource, long p_lUserId, MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---------------------------Call of ExplodePdf");

            var l_oReturnString = new ReturnString {Value = p_sFileSource};

            try
            {
                //Get the import document full path
                string originalPdfFileToSplit = GetImportDocumentFullPath(p_sFileSource, p_lUserId);

                //Copy the original file 
                string copiedPdfFileToSplit = Path.Combine(Path.GetDirectoryName(originalPdfFileToSplit),
                                                           "C_" + p_sFileSource);
                if (!File.Exists(copiedPdfFileToSplit))
                    File.Copy(originalPdfFileToSplit, copiedPdfFileToSplit);

                //Get nmber of page
                var l_iNumberPagePDF = GetPageCountFromPdfFullPath(copiedPdfFileToSplit, p_oMessageRequest);

                //If one Page in PDF, no execute Process
                if (l_iNumberPagePDF != null)
                {
                    int pagePageCount = Convert.ToInt16(l_iNumberPagePDF.Value);
                    if (pagePageCount > 1)
                    {
                        PdfReader l_oReader = new PdfReader(copiedPdfFileToSplit);

                        for (int i = 1; i <= pagePageCount; i++)
                        {
                            //Extract the page
                            string extractedPdfPage =
                                Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.InputDirectory"),
                                             p_lUserId + "\\" + i.ToString("00000") + "_" + p_sFileSource);
                            string extractedThumbnailPdfPage =
                                Path.Combine(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.OutputDirectory"),
                                             p_lUserId + "\\" + i.ToString("00000") + "_" + p_sFileSource) +
                                Constant.ImageFileFormat.JPG.szGetDescription();

                            Treatments.ExtractPdfPage(l_oReader, i, extractedPdfPage, copiedPdfFileToSplit);

                            using (var l_oSaveJpgGdPicture = new Treatments())
                            {
                                //ThumbNail generation
                                l_oSaveJpgGdPicture.SavePdfPageToJpg(extractedPdfPage, 60, extractedThumbnailPdfPage);
                            }

                            //Resize ThumbNail  
                            var l_oResizeThumbNail = new Treatments();
                            l_oResizeThumbNail.ResizeImage(
                                extractedPdfPage + Constant.ImageFileFormat.JPG.szGetDescription(),
                                extractedPdfPage + Constant.ImageFileFormat.JPG.szGetDescription(),
                                int.Parse(ConfigurationManager.AppSettings.Get("ImageWidth")),
                                int.Parse(ConfigurationManager.AppSettings.Get("ImageHeigth"))
                                );
                        }

                        //Delete original file and the copied file
                        DeleteImportDocument(new List<String> {p_sFileSource}, p_lUserId, p_oMessageRequest);
                        if (File.Exists(copiedPdfFileToSplit))
                            File.Delete(copiedPdfFileToSplit);
                    }
                }
            }
            catch (Exception Ex)
            {
                LogManager.Instance().LogError(
                    "-------------------------------------- Exception in ExplodePdf. Exception[" + Ex.StackTrace + "]");
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---ExplodePdf-----------------");
            LogManager.Instance().LogInfo("END OF WCF SERVICE CALL ---------------------");
            return l_oReturnString;
        }


        /// <summary>
        ///   Carve the file into p_iNbPart parts
        /// </summary>
        /// <param name="p_lstDocumentName"> </param>
        /// <param name="p_lUserId"> </param>
        /// <param name="p_iNbPart"> </param>
        /// <param name="p_oMessageRequest"> </param>
        /// <returns> </returns>
        public ReturnString CarveImportFiles(List<string> p_lstDocumentName, string p_sDirectoryName, long p_lUserId,
                                             int p_iNbPart, MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---CarveImportFiles----------------------------------");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            var l_oReturnString = new ReturnString();

            try
            {
                var l_oTreatments = new Treatments();
                FileInfo l_CurrentFile;

                int l_iHeigthGdPictureInfo = 0;
                int l_iWidthGdPictureInfo = 0;
                int l_oCloneImage = 0;

                LicenseGdPicture();

                foreach (var l_sOneFileToCrop in p_lstDocumentName)
                {
                    int m_iImageID;
                    l_CurrentFile = new FileInfo(GetImportDocumentFullPath(l_sOneFileToCrop, p_lUserId));
                    var ThumbnailPath = Path.GetDirectoryName(GetThumbDocumentFullPath(l_sOneFileToCrop, p_lUserId));
                    var l_lstCarvedFiles = new List<string>();
                    var l_sImageFileName = Path.GetFileNameWithoutExtension(l_CurrentFile.FullName);
                    string l_sCurrentCarvedImage = null;

                    m_iImageID = m_oGdPictureImaging.CreateGdPictureImageFromFile(l_CurrentFile.FullName);
                    l_iHeigthGdPictureInfo = m_oGdPictureImaging.GetHeight(m_iImageID);
                    l_iWidthGdPictureInfo = m_oGdPictureImaging.GetWidth(m_iImageID);
                    //m_oGdPictureImaging.GetImageFormat 

                    var l_iSliceWidth = 0;
                    var l_iSliceHeigth = 0;
                    var l_iSliceX = 0;
                    var l_iSliceY = 0;
                    if (l_iHeigthGdPictureInfo >= l_iWidthGdPictureInfo)
                    {
                        l_iSliceWidth = l_iWidthGdPictureInfo;
                        l_iSliceHeigth = l_iHeigthGdPictureInfo/p_iNbPart;
                    }
                    else
                    {
                        l_iSliceWidth = l_iWidthGdPictureInfo/p_iNbPart;
                        l_iSliceHeigth = l_iHeigthGdPictureInfo;
                    }

                    var l_sWorkingDirectory = l_CurrentFile.DirectoryName;

                    //First Image
                    l_sCurrentCarvedImage = Path.Combine(l_sWorkingDirectory,
                                                         l_sImageFileName + "_1" + l_CurrentFile.Extension);
                    l_oCloneImage = m_oGdPictureImaging.CreateClonedGdPictureImageArea(m_iImageID, 0, 0, l_iSliceWidth,
                                                                                       l_iSliceHeigth);

                    if (l_CurrentFile.Extension.ToLower().Equals(Constant.ImageFileFormat.JPG.szGetDescription())
                        || l_CurrentFile.Extension.ToLower().Equals(Constant.ImageFileFormat.JPEG.szGetDescription()))
                    {
                        m_oGdPictureImaging.SaveAsJPEG(l_oCloneImage, l_sCurrentCarvedImage);
                    }
                    else if (l_CurrentFile.Extension.ToLower().Equals(Constant.ImageFileFormat.GIF.szGetDescription()))
                    {
                        m_oGdPictureImaging.SaveAsGIF(l_oCloneImage, l_sCurrentCarvedImage);
                    }
                    else if (l_CurrentFile.Extension.ToLower().Equals(Constant.ImageFileFormat.TIF.szGetDescription())
                             ||
                             l_CurrentFile.Extension.ToLower().Equals(Constant.ImageFileFormat.TIFF.szGetDescription()))
                    {
                        m_oGdPictureImaging.SaveAsTIFF(l_oCloneImage, l_sCurrentCarvedImage,
                                                       m_oGdPictureImaging.GetTiffCompression(m_iImageID));
                    }
                    else if (l_CurrentFile.Extension.ToLower().Equals(Constant.ImageFileFormat.BMP.szGetDescription()))
                    {
                        m_oGdPictureImaging.SaveAsBMP(l_oCloneImage, l_sCurrentCarvedImage);
                    }
                    else if (l_CurrentFile.Extension.ToLower().Equals(Constant.ImageFileFormat.PNG.szGetDescription()))
                    {
                        m_oGdPictureImaging.SaveAsPNG(l_oCloneImage, l_sCurrentCarvedImage);
                    }
                    else if (l_CurrentFile.Extension.ToLower().Equals(Constant.ImageFileFormat.ICO.szGetDescription()))
                    {
                        m_oGdPictureImaging.SaveAsICO(l_oCloneImage, l_sCurrentCarvedImage);
                    }


                    l_lstCarvedFiles.Add(l_sCurrentCarvedImage);
                    l_oReturnString.Value = Path.GetFileName(l_sCurrentCarvedImage);

                    // All other images
                    for (var i = 1; i < p_iNbPart; i++)
                    {
                        if (l_iHeigthGdPictureInfo >= l_iWidthGdPictureInfo)
                        {
                            l_iSliceWidth = l_iWidthGdPictureInfo;
                            l_iSliceHeigth = l_iHeigthGdPictureInfo/p_iNbPart;
                            l_iSliceY = l_iSliceHeigth*i;
                            l_iSliceX = 0;
                        }
                        else
                        {
                            l_iSliceWidth = l_iWidthGdPictureInfo/p_iNbPart;
                            l_iSliceHeigth = l_iHeigthGdPictureInfo;
                            l_iSliceY = 0;
                            l_iSliceX = l_iSliceWidth*i;
                        }

                        l_sCurrentCarvedImage = Path.Combine(l_sWorkingDirectory,
                                                             l_sImageFileName + "_" + (i + 1).ToString("0") +
                                                             l_CurrentFile.Extension);
                        l_oCloneImage = m_oGdPictureImaging.CreateClonedGdPictureImageArea(m_iImageID, l_iSliceX,
                                                                                           l_iSliceY, l_iSliceWidth,
                                                                                           l_iSliceHeigth);

                        if (l_CurrentFile.Extension.ToLower().Equals(Constant.ImageFileFormat.JPG.szGetDescription())
                            ||
                            l_CurrentFile.Extension.ToLower().Equals(Constant.ImageFileFormat.JPEG.szGetDescription()))
                        {
                            m_oGdPictureImaging.SaveAsJPEG(l_oCloneImage, l_sCurrentCarvedImage);
                        }
                        else if (l_CurrentFile.Extension.ToLower().Equals(Constant.ImageFileFormat.GIF.szGetDescription()))
                        {
                            m_oGdPictureImaging.SaveAsGIF(l_oCloneImage, l_sCurrentCarvedImage);
                        }
                        else if (l_CurrentFile.Extension.ToLower().Equals(
                            Constant.ImageFileFormat.TIF.szGetDescription())
                                 ||
                                 l_CurrentFile.Extension.ToLower().Equals(
                                     Constant.ImageFileFormat.TIFF.szGetDescription()))
                        {
                            m_oGdPictureImaging.SaveAsTIFF(l_oCloneImage, l_sCurrentCarvedImage,
                                                           m_oGdPictureImaging.GetTiffCompression(m_iImageID));
                        }
                        else if (
                            l_CurrentFile.Extension.ToLower().Equals(
                                Constant.ImageFileFormat.BMP.szGetDescription()))
                        {
                            m_oGdPictureImaging.SaveAsBMP(l_oCloneImage, l_sCurrentCarvedImage);
                        }
                        else if (
                            l_CurrentFile.Extension.ToLower().Equals(
                                Constant.ImageFileFormat.PNG.szGetDescription()))
                        {
                            m_oGdPictureImaging.SaveAsPNG(l_oCloneImage, l_sCurrentCarvedImage);
                        }
                        else if (
                            l_CurrentFile.Extension.ToLower().Equals(
                                Constant.ImageFileFormat.ICO.szGetDescription()))
                        {
                            m_oGdPictureImaging.SaveAsICO(l_oCloneImage, l_sCurrentCarvedImage);
                        }


                        m_oGdPictureImaging.SaveAsJPEG(l_oCloneImage, l_sCurrentCarvedImage);

                        l_lstCarvedFiles.Add(l_sCurrentCarvedImage);
                    }

                    foreach (var l_sFileToThumb in l_lstCarvedFiles)
                    {
                        l_oTreatments.CreateThumb(l_sFileToThumb,
                                                  GetThumbDocumentFullPath(Path.GetFileName(l_sFileToThumb), p_lUserId,
                                                                           p_sDirectoryName));
                    }


                    m_oGdPictureImaging.ReleaseGdPictureImage(m_iImageID);
                }


                //m_oGdPictureImaging.ClearGdPicture();
                DeleteImportDocument(p_lstDocumentName, p_lUserId, p_oMessageRequest);
            }
            catch (Exception ex)
            {
                l_oReturnString =
                    new ReturnString("------------- EXCEPTION IN WCF CarveImportFiles EXCEPTION[" + DateTime.Now + "]",
                                     new Exception(ex.Message));
                l_oReturnString.IsValid = false;
                LogManager.Instance().LogError(l_oReturnString.FullErrorMessage);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---CarveImportFiles-----------------");
            LogManager.Instance().LogInfo("END OF WCF SERVICE CALL ---------------------");
            return l_oReturnString;
        }

        /// <summary>
        ///   Return the page number of a text in a document
        /// </summary>
        /// <param name="p_sFileName"> File name of the document </param>
        /// <param name="p_iUserId"> The user identifier </param>
        /// <param name="p_sSearchedWords"> Words to search </param>
        /// <param name="p_oMessageRequest"> Security Object </param>
        /// <returns> The page where the word has been found </returns>
        public ReturnLong SearchTextInImportDocument(string p_sFileName, long p_iUserId, string p_sSearchedWords,
                                                     int p_lStartPage, MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---SearchTextInImportDocument-----p_sFileName[" + p_sFileName +
                                          "]---p_iUserId[" + p_iUserId + "]----p_sSearchedWords[" +
                                          p_sSearchedWords + "]");

            Treatments.CheckApplicationRequestKey(p_oMessageRequest);

            ReturnLong l_oReturnLong = SearchTextInDocument(GetImportDocumentFullPath(p_sFileName, p_iUserId),
                                                            p_sSearchedWords, p_lStartPage, p_oMessageRequest);

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---SearchTextInImportDocument-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return l_oReturnLong;
        }

        /// <summary>
        ///   Seach a word in a document
        /// </summary>
        /// <param name="p_sFileNameFullPath"> File name full path of the document </param>
        /// <param name="p_sSearchedWords"> Words to search </param>
        /// <param name="p_lStartPage"> Start page for the search engine </param>
        /// <param name="p_oMessageRequest"> Security Object </param>
        /// <returns> The page where the word has been found </returns>
        public ReturnLong SearchTextInDocument(string p_sFileNameFullPath, string p_sSearchedWords, int p_lStartPage,
                                               MessageRequest p_oMessageRequest)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WFC SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---SearchTextInDocument-----p_sFileNameFullPath[" +
                                          p_sFileNameFullPath + "]----p_sSearchedWords[" +
                                          p_sSearchedWords + "]");


            var l_oReturnLong = new ReturnLong();
            l_oReturnLong.Value = -1;
            try
            {
                Treatments.CheckApplicationRequestKey(p_oMessageRequest);

                #region Aspose licencing

                var wordLicense = new License();
                wordLicense.SetLicense("Aspose.Total.lic");

                var pdfLicense = new Aspose.Pdf.License();
                pdfLicense.SetLicense("Aspose.Total.lic");


                var pdfkitLicense = new Aspose.Pdf.Kit.License();
                pdfkitLicense.SetLicense("Aspose.Total.lic");

                #endregion

                FileInfo l_oFileInfo = new FileInfo(p_sFileNameFullPath);

                MemoryStream l_oCurrent_ms = new MemoryStream();

                if (l_oFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.DOC.szGetDescription())
                    || l_oFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.DOCX.szGetDescription())
                    || l_oFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.RTF.szGetDescription()))
                {
                    #region DOCX / DOC / RTF

                    var l_oWordDocument = new Aspose.Words.Document(l_oFileInfo.FullName);

                    var l_oPdfOptions = new PdfOptions
                                            {
                                                TextCompression = PdfTextCompression.None,
                                                IsPreserveFormFields = true,
                                                JpegQuality = 100
                                            };

                    if (p_lStartPage <= l_oWordDocument.PageCount)
                    {
                        for (var i = p_lStartPage; i < l_oWordDocument.PageCount; i++)
                        {
                            l_oWordDocument.SaveToPdf(i, 1, l_oCurrent_ms, l_oPdfOptions);

                            if (FindWordInMemoryStream(l_oCurrent_ms, p_sSearchedWords))
                            {
                                l_oReturnLong.Value = i + 1;
                                break;
                            }
                        }
                    }

                    #endregion
                }
                else if (l_oFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.PDF.szGetDescription()))
                {
                    #region PDF

                    p_lStartPage++;

                    PdfReader l_oReader = new PdfReader(l_oFileInfo.FullName);
                    string l_sExtractedText = string.Empty;


                    ITextExtractionStrategy l_oIts = new SimpleTextExtractionStrategy();
                    if (p_lStartPage <= l_oReader.NumberOfPages)
                    {
                        for (var i = p_lStartPage; i < l_oReader.NumberOfPages; i++)
                        {
                            l_sExtractedText = PdfTextExtractor.GetTextFromPage(l_oReader, i, l_oIts);
                            l_sExtractedText =
                                Encoding.UTF8.GetString(
                                    Encoding.Convert(Encoding.Default, Encoding.UTF8,
                                                     Encoding.Default.GetBytes(l_sExtractedText)));

                            if (l_sExtractedText.ToLower().IndexOf(p_sSearchedWords.ToLower()) > 0)
                            {
                                l_oReturnLong.Value = i;
                                break;
                            }
                        }
                    }
                    PDFManager l_oParser = new PDFManager();
                    if (p_lStartPage <= l_oReader.NumberOfPages)
                    {
                        for (var i = p_lStartPage; i < l_oReader.NumberOfPages; i++)
                        {
                            l_sExtractedText = l_oParser.ExtractTextFromPDFBytes(l_oReader.GetPageContent(i));

                            if (l_sExtractedText.ToLower().IndexOf(p_sSearchedWords.ToLower()) > 0)
                            {
                                l_oReturnLong.Value = i;
                                break;
                            }
                        }
                    }

                    #endregion
                }
                else if (l_oFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.PPT.szGetDescription())
                         || l_oFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.PPTX.szGetDescription()))
                {
                    #region PPTX / PPT

                    p_lStartPage++;

                    var l_oPresentation = new Presentation(l_oFileInfo.FullName);
                    for (var i = p_lStartPage; i < l_oPresentation.Slides.Count; i++)
                    {
                        if (FindTextInPowerPointSlide(l_oPresentation.Slides[i], p_sSearchedWords))
                        {
                            l_oReturnLong.Value = i;
                            break;
                        }
                    }

                    #region Version avec conversion pdf

                    //if (p_lStartPage.Equals(0))
                    //    p_lStartPage = 1;

                    //#region Aspose licencing
                    //var pdfpptLicense = new Aspose.Pdf.License();
                    //pdfpptLicense.SetLicense("Aspose.Total.lic");

                    //var pptLicense = new Aspose.Slides.License();
                    //pptLicense.SetLicense("Aspose.Total.lic");

                    //#endregion

                    //Aspose.Slides.Presentation l_oPresentation = new Aspose.Slides.Presentation(l_oFileInfo.FullName);
                    //Aspose.Slides.Presentation l_oWorkingPresentation = l_oPresentation;
                    //for (var i = p_lStartPage-1; i < l_oPresentation.Slides.Count; i++)
                    //{
                    //    MemoryStream l_oMemorystream = new MemoryStream();
                    //    l_oMemorystream = GetAsposeSlidePresentationSlide(l_oWorkingPresentation, p_lStartPage);

                    //    if (FindWordInMemoryStream(l_oMemorystream, p_sSearchedWords))
                    //    {
                    //        l_oReturnLong.Value = i+1;
                    //        break;
                    //    }
                    //    l_oWorkingPresentation = l_oPresentation;
                    //}

                    #endregion

                    #endregion
                }
                else if (l_oFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.XLS.szGetDescription())
                         || l_oFileInfo.Extension.ToLower().Equals(Constant.DocumentFileFormat.XLSX.szGetDescription()))
                {
                    #region XLS/XLSX

                    p_lStartPage++;

                    #region Aspose licencing

                    var xlsLicense = new Aspose.Cells.License();
                    xlsLicense.SetLicense("Aspose.Total.lic");

                    #endregion

                    var l_oWorkbook = new Workbook(l_oFileInfo.FullName);

                    for (var i = p_lStartPage; i < l_oWorkbook.Worksheets.Count; i++)
                    {
                        var l_oCell = l_oWorkbook.Worksheets[i].Cells.FindStringContains(p_sSearchedWords, null);
                        if (l_oCell != null)
                        {
                            l_oReturnLong.Value = i;
                            break;
                        }
                    }

                    #endregion
                }
            }
            catch (Exception ex)
            {
                l_oReturnLong =
                    new ReturnLong(
                        "------------- EXCEPTION IN WCF SearchTextInDocument EXCEPTION[" + DateTime.Now + "]",
                        new Exception(ex.Message));
                LogManager.Instance().LogError(l_oReturnLong.FullErrorMessage);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---SearchTextInDocument-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return l_oReturnLong;
        }

        /// <summary>
        ///   Does the barcode reconition.
        /// </summary>
        /// <param name="request"> The request. </param>
        /// <returns> </returns>
        public List<ImageRio> DoBarcodeRecognition(List<string> images, long p_lUserId, bool p_bOrderByDescending,
                                                   MessageRequest p_oMessageRequest)
        {
            List<ImageRio> result = new List<ImageRio>();

            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---DoBarcodeReconition------p_lUserId(" +
                                          p_lUserId.ToString() + ")--------------------" + DateTime.Now);

            try
            {
                //Get all files without directories
                List<ImageRio> files = GetImportThumbNailListFromPath(p_lUserId, null, p_bOrderByDescending,
                                                                      p_oMessageRequest);

                using (Treatments traitement = new Treatments())
                {
                    foreach (var item in images)
                    {
                        var currentImage = files.Single(p => Utils.RemoveExtension(p.Name) == item);
                        if (currentImage != null)
                        {
                            currentImage.Clear();
                            if (!currentImage.isDirectory)
                            {
                                var l_sImageFullPath =
                                    GetImportDocumentFullPath(Utils.RemoveExtension(currentImage.Name), p_lUserId);
                                currentImage.OriginalBarcodes.AddRange(traitement.DoBarcodeRecognition(l_sImageFullPath));
                            }

                            result.Add(currentImage);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.Instance().LogError("------------Exception in DoBarcodeReconition" +
                                               ex.Message + " ----- " + DateTime.Now);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---DoBarcodeReconition-----------------");
            LogManager.Instance().LogInfo("END OF WFC SERVICE CALL ---------------------");

            return result;
        }

        /// <summary>
        ///   Duplicates a file from one folder to another with controlled existence of the file Destination
        /// </summary>
        /// <param name="p_sDocumentNameFullPathSource"> </param>
        /// <param name="p_sDocumentNameFullPathDestination"> </param>
        /// <param name="p_sStockPath"> </param>
        /// <returns> </returns>
        public ReturnBoolean Duplicate_Document(string p_sDocumentNameFullPathSource,
                                                string p_sDocumentNameFullPathDestination, string p_sStockPath)
        {
            LogManager.ConfigFile(ConfigurationManager.AppSettings.Get("Rio.WCF.Services.Configuration"));
            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("WCF SERVICE CALLED --------------------------");
            LogManager.Instance().LogInfo("---DuplicateDocument-----p_sDocumentNameFullPathSource[" +
                                          p_sDocumentNameFullPathSource +
                                          "] p_sDocumentNameFullPathDestination[" +
                                          p_sDocumentNameFullPathDestination + "] p_sStockPath[" +
                                          p_sStockPath + "]");

            var l_oReturnBooleanDuplicate = new ReturnBoolean();
            l_oReturnBooleanDuplicate.IsValid = true;

            try
            {
                string l_sDocumentName = Path.GetFileName(p_sDocumentNameFullPathSource);
                string l_sDocumentSansExtension = Path.GetFileNameWithoutExtension(p_sDocumentNameFullPathSource);
                string l_sPathSource = Path.GetDirectoryName(p_sDocumentNameFullPathSource);

                //Verifies the existence of destination Folder
                string l_sPathDestination = Path.GetDirectoryName(p_sDocumentNameFullPathDestination);
                string l_sFullPathDestination = Path.Combine(p_sStockPath, l_sPathDestination);
                Treatments.CheckDirectory(l_sFullPathDestination);

                //Copy the file in new folder
                string l_sFullPathSourceDocument = Path.Combine(p_sStockPath, p_sDocumentNameFullPathSource);
                string l_sFullPathDestinationDocument = Path.Combine(p_sStockPath, p_sDocumentNameFullPathDestination);
                File.Copy(l_sFullPathSourceDocument, l_sFullPathDestinationDocument);

                //Verifies the existence of destination Folder ThumbNail
                string l_sPathThumbNail = Path.Combine(p_sStockPath, "ThumbNail");
                string l_sFullPathThumbNailDestination = Path.Combine(l_sPathThumbNail, l_sPathDestination);
                string l_sFullPathThumbNailSource = Path.Combine(l_sPathThumbNail, l_sPathSource);
                Treatments.CheckDirectory(l_sFullPathThumbNailDestination);
                string l_sFullPathOutThumbNailDestination = Path.Combine(l_sFullPathThumbNailDestination,
                                                                         l_sDocumentSansExtension +
                                                                         Constant.ImageFileFormat.JPG.szGetDescription());
                string l_sFullPathOutThumbNailSource = Path.Combine(l_sFullPathThumbNailSource,
                                                                    l_sDocumentSansExtension +
                                                                    Constant.ImageFileFormat.JPG.szGetDescription());
                File.Copy(l_sFullPathOutThumbNailSource, l_sFullPathOutThumbNailDestination);
                l_oReturnBooleanDuplicate.Value = true;
                l_oReturnBooleanDuplicate.IsValid = true;
            }

            catch (Exception ex)
            {
                l_oReturnBooleanDuplicate.IsValid = false;
                l_oReturnBooleanDuplicate.Value = false;
                l_oReturnBooleanDuplicate.ErrorMessage =
                    "------------- EXCEPTION IN WCF Duplicate_Document EXCEPTION[" + DateTime.Now + "]Exception " +
                    ex.Message;
                LogManager.Instance().LogError("EXCEPTION IN WCF DuplicateDocument EXCEPTION[" +
                                               DateTime.Now + "] Exception " + ex.Message);
            }

            LogManager.Instance().LogInfo(string.Empty);
            LogManager.Instance().LogInfo("---DuplicateDocument-----------------");
            LogManager.Instance().LogInfo("END OF WCF SERVICE CALL ---------------------");

            return l_oReturnBooleanDuplicate;
        }

        #endregion

        #region Class Methods

        private static ArrayList GenerateFileList(string p_sDirirectoryToCompress)
        {
            ArrayList l_oFiles = new ArrayList();
            bool l_bEmpty = true;
            foreach (string file in Directory.GetFiles(p_sDirirectoryToCompress)) // add each file in directory
            {
                l_oFiles.Add(file);
                l_bEmpty = false;
            }

            if (l_bEmpty)
            {
                if (Directory.GetDirectories(p_sDirirectoryToCompress).Length == 0)
                    // if directory is completely empty, add it
                {
                    l_oFiles.Add(p_sDirirectoryToCompress + @"/");
                }
            }

            foreach (string dirs in Directory.GetDirectories(p_sDirirectoryToCompress)) // recursive
            {
                foreach (object obj in GenerateFileList(dirs))
                {
                    l_oFiles.Add(obj);
                }
            }
            return l_oFiles; // return file list
        }

        #endregion
    }
}